id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
sql-server-ec2-005
sql-server-ec2.pdf
5
and recovery design for SQL Server on Amazon EC2 is flexible, depending on your RTO and RPO requirements. AWS provides the ability to perform server-level backups using Windows Volume Shadow Copy Service (VSS)-enabled Amazon Elastic Block Store (Amazon EBS) snapshots and with AWS Backup. You can also perform database-level backups using native backup and restore procedures for SQL Server databases. Database-level backups can be stored on Amazon EBS, FSx for Windows File Server, or Amazon Simple Storage Service using AWS Storage Gateway. For more information about backing up SQL Server on Amazon EC2, see Backup and restore options for SQL Server on Amazon EC2 on the AWS Prescriptive Guidance website. Billing A SQL Server on Amazon EC2 instance is charged by the second, with a minimum of 1 minute. Applied rates are based on the type and size of the selected instance, the edition of SQL Server when using a license-included instance, along with the cost of any additional services, such as storage or networking. AWS provides a variety of instance families that are favorable to the performance requirements of SQL Server workloads. You can rent an instance based on your unique CPU, memory, and storage throughput requirements. You can also stop or terminate an instance at any time to pause or stop billing for the instance. The main advantage of the On-Demand model is the ability to save on CAPEX when an instance is no longer required. Warning Any data on Amazon EC2 instance store volumes are lost if your instance is stopped or terminated. You'll still incur costs for EBS volumes when your instance is stopped. For more information, see Stop and start your instance in the Amazon EC2 User Guide. High availability and disaster recovery (HADR) You can take advantage of Windows Server Failover Cluster for high availability and disaster recovery (HADR) with SQL Server on Amazon EC2. SQL Server on Amazon EC2 supports both Concepts and terminology 7 Microsoft SQL Server on Amazon EC2 User Guide failover cluster instances (SQL FCIs) and Always On availability groups (AG). For more information see How do I create a SQL Server Always On availability group cluster in the AWS Cloud? in the AWS knowledge center. Instance A SQL Server on Amazon EC2 instance is a virtual (or bare metal) server that runs in the AWS Cloud and can be provisioned on demand. The subscriber rents the virtual server by the hour/minute/ second, and can use it to deploy specific configurations of SQL Server. For more information about On-Demand instances, see On-Demand instances in the Amazon EC2 User Guide. An Amazon EC2 Dedicated Hosts is a physical server with EC2 instance capacity that is fully dedicated to your use. Dedicated Hosts allow you to use your existing per-socket, per-core, or per-VM Microsoft SQL Server software licenses. For more information about Dedicated Hosts, see Dedicated Hosts in the Amazon EC2 User Guide. Instance types AWS provides various types of instances with different CPU, memory, storage, and networking configurations to support your application requirements. Each instance type is available in various sizes to address specific workload requirements. Instance types are grouped into families according to target application profiles, such as general purpose, compute-optimized, memory-optimized, and storage-optimized. The memory-optimized family of instances is a popular choice for SQL Server on Amazon EC2 because instances in this family have a high memory to CPU ratio for optimal performance. You can choose bare metal instances to support capabilities such as Always Encrypted with secure enclaves on Amazon EC2 bare metal instances. For more information about individual and families of instance types, see Amazon EC2 Instance Types in the AWS product pages. Some instance types support instance store volumes, which provide temporary block-level storage for the instance. If your instance has instance store volumes, we recommend that you place tempdb on an instance store volume. This can improve performance and decrease costs. For more information, see Place tempdb in an instance store. Launching SQL Server on Amazon EC2 SQL Server on Amazon EC2 instances can be launched directly from the Amazon EC2 console, with AWS CloudFormation, by using AWS Tools for PowerShell, or by using the AWS CLI. For a guided deployment of Microsoft SQL Server, use AWS Launch Wizard. Concepts and terminology 8 Microsoft SQL Server on Amazon EC2 Security User Guide AWS supports all security standards and compliance certifications, such as PCI-DSS, HIPAA/ HITECH, FedRAMP, GDPR, FIPS, FIPS 140-2, and more. These standards enable you to build a fully compliant application on Amazon EC2. AWS also supports all SQL Server security features such as Transparent Data Encryption (TDE) and Always Encrypted with Secure Enclaves (when using bare metal instances). Security and compliance is a shared responsibility between you and AWS. This shared model helps to relieve your operational burden because AWS operates, manages, and
sql-server-ec2-006
sql-server-ec2.pdf
6
use AWS Launch Wizard. Concepts and terminology 8 Microsoft SQL Server on Amazon EC2 Security User Guide AWS supports all security standards and compliance certifications, such as PCI-DSS, HIPAA/ HITECH, FedRAMP, GDPR, FIPS, FIPS 140-2, and more. These standards enable you to build a fully compliant application on Amazon EC2. AWS also supports all SQL Server security features such as Transparent Data Encryption (TDE) and Always Encrypted with Secure Enclaves (when using bare metal instances). Security and compliance is a shared responsibility between you and AWS. This shared model helps to relieve your operational burden because AWS operates, manages, and controls the components from the host operating system and virtualization layer to the physical security of the facilities in which the service operates. For SQL Server on Amazon EC2, you assume responsibility and management of the guest operating system, including updates and security patches, other associated application software, and the configuration of AWS provided security group firewalls. For more information about the shared responsibility model, see Shared Responsibility Model. Storage AWS provides many storage options to host your database files. In addition to EBS volume types, you can attach volumes to SQL Server on Amazon EC2 instances using an Amazon FSx managed file system service, such as FSx for Windows File Server and Amazon FSx for NetApp ONTAP. Some instance types provide an Amazon EC2 instance store which provides temporary block level storage on NVMe solid state drive (SSD) disks that are physically attached to the host computer. For more information, see Best practices for deploying Microsoft SQL Server on Amazon EC2 on the AWS Prescriptive Guidance website. Best practices and recommendations for SQL Server clustering on Amazon EC2 You can configure Microsoft SQL Server on Amazon EC2 instances for high availability. SQL Server Always On availability groups offer high availability without the requirement for shared storage. The list of best practices in this topic, in addition to the prerequisites listed at Prerequisites, Restrictions, and Recommendations for Always On availability groups, can help you optimize operating a SQL Server Always On availability groups on AWS. The practices listed in this topic also offer a method to gather logs. SQL Clustering best practices 9 Microsoft SQL Server on Amazon EC2 User Guide Note When nodes are deployed in different Availability Zones, or in different subnets within the same Availability Zone, they should be treated as a multi-subnet cluster. Keep this in mind as you apply these best practices and when you address possible failure scenarios. Contents • Assign IP addresses • Cluster properties • Cluster quorum votes and 50/50 splits in a multi-site cluster • DNS registration • Elastic Network Adapters (ENAs) • Multi-site clusters and EC2 instance placement • Instance type selection • Assign elastic network interfaces and IPs to the instance • Heartbeat network • Configure the network adapter in the OS • IPv6 • Host record TTL for SQL Availability Group Listeners • Logging • NetBIOS over TCP • NetFT Virtual Adapter • Set possible owners • Tune the failover thresholds • Witness importance and Dynamic Quorum Architecture • Troubleshoot Assign IP addresses Each cluster node should have one elastic network interface assigned that includes three private IP addresses on the subnet: a primary IP address, a cluster IP address, and an Availability Group Assign IP addresses 10 Microsoft SQL Server on Amazon EC2 User Guide IP address. The operating system (OS) should have the NIC configured for DHCP. It should not be set for a static IP address because the IP addresses for the cluster IP and Availability Group will be handled virtually in the Failover Cluster Manager. The NIC can be configured for a static IP as long as it is configured to only use the primary IP of eth0. If the other IPs are assigned to the NIC, it can cause network drops for the instance during failover events. When the network drops because the IPs are incorrectly assigned, or when there is a failover event or network failure, it is not uncommon to see the following event log entries at the time of failure. Isatap interface isatap.{9468661C-0AEB-41BD-BB8C-1F85981D5482} is no longer active. Isatap interface isatap.{9468661C-0AEB-41BD-BB8C-1F85981D5482} with address fe80::5efe:169.254.1.105 has been brought up. Because these messages seem to describe network issues, you could potentially mistake the cause of the outage or failure as a network error. However, these errors describe a symptom, rather than cause, of the failure. ISATAP is a tunneling technology that uses IPv6 over IPv4. When the IPv4 connection fails, the ISATAP adapter also fails. When the network issues are resolved, these entries should no longer appear in the event logs. Alternately, you can reduce network errors by safely disabling ISATAP with the following command. netsh int ipv6 isatap set state disabled When you run this command, the adapter is removed from Device
sql-server-ec2-007
sql-server-ec2.pdf
7
seem to describe network issues, you could potentially mistake the cause of the outage or failure as a network error. However, these errors describe a symptom, rather than cause, of the failure. ISATAP is a tunneling technology that uses IPv6 over IPv4. When the IPv4 connection fails, the ISATAP adapter also fails. When the network issues are resolved, these entries should no longer appear in the event logs. Alternately, you can reduce network errors by safely disabling ISATAP with the following command. netsh int ipv6 isatap set state disabled When you run this command, the adapter is removed from Device Manager. This command should be run on all nodes. It does not impact the ability of the cluster to function. Instead, when the command has been run, ISATAP is no longer used. However, because this command might cause unknown impacts on other applications that use ISATAP, you should test it. Cluster properties To see the complete cluster configuration, run the following PowerShell command. Get-Cluster | Format-List -Property * Cluster quorum votes and 50/50 splits in a multi-site cluster To learn how the cluster quorum works and what to expect if a failure occurs, see Understanding Cluster and Pool Quorum. Cluster properties 11 Microsoft SQL Server on Amazon EC2 DNS registration User Guide In Windows Server 2012, Failover Clustering, by default, attempts to register each DNS node under the cluster name. This is acceptable for applications that are aware the SQL target is configured for multi-site. However, when the client is not configured this way, it can result in timeouts, delays, and application errors due to attempts to connect to each individual node and failing on the inactive ones. To prevent these problems, the Cluster Resource parameter RegisterAllProvidersIp must be changed to 0. For more information, see RegisterAllProvidersIP Setting and Multi-subnet Clustered SQL + RegisterAllProvidersIP + SharePoint 2013. The RegisterAllProvidersIp can be modified with the following PowerShell script. Import-Module FailoverClusters $cluster = (Get-ClusterResource | where {($_.ResourceType -eq "Network Name") -and ($_.OwnerGroup -ne "Cluster Group")}).Name Get-ClusterResource $cluster | Set-ClusterParameter RegisterAllProvidersIP 0 Get-ClusterResource $cluster |Set-ClusterParameter HostRecordTTL 300 Stop-ClusterResource $cluster Start-ClusterResource $cluster In addition to setting the Cluster Resource parameter to 0, you must ensure that the cluster has permissions to modify the DNS entry for your cluster name. 1. Log in to the Domain Controller (DC) for the domain, or a server that hosts the forward lookup zone for the domain. 2. Launch the DNS Management Console and locate the A record for the cluster. 3. Choose or right-click the A record, and choose Properties. 4. Choose Security. 5. Choose Add. 6. Choose Object Types..., select the box for Computers, and choose OK. 7. 8. Enter the name of the cluster resource object and choose Check name and OK if resolve. Select the check box for Full Control. 9. Choose OK. DNS registration 12 Microsoft SQL Server on Amazon EC2 User Guide Elastic Network Adapters (ENAs) AWS has identified known issues with some clustering workloads running on ENA driver version 1.2.3. We recommend upgrading to the latest version, and adjusting settings on the NIC in the operating system. For the latest versions, see Amazon ENA Driver Versions. The first setting, which applies to all systems, increases Receive Buffers, which you can do with the following example PowerShell command. Set-NetAdapterAdvancedProperty -Name (Get-NetAdapter | Where-Object {$_.InterfaceDescription -like '*Elastic*'}).Name -DisplayName "Receive Buffers" - DisplayValue 8192 For instances with more than 16 vCPUs, we recommend preventing RSS from running on CPU 0. Run the following command. Set-NetAdapterRss -name (Get-NetAdapter | Where-Object {$_.InterfaceDescription -like '*Elastic*'}).Name -Baseprocessorgroup 0 -BaseProcessorNumber 1 Multi-site clusters and EC2 instance placement Each cluster is considered a multi-site cluster. The EC2 service does not share IP addresses virtually. Each node must be in a unique subnet. Though not required, we recommend that each node also be in a unique Availability Zone. Instance type selection The type of instance recommended for Windows Server Failover Clustering depends on the workload. For production workloads, we recommend instances that support Amazon Elastic Block Store (Amazon EBS) optimization and enhanced networking. For more information, see EBS optimization and Enhanced networking in the Amazon EC2 User Guide. Assign elastic network interfaces and IPs to the instance Each node in an EC2 cluster should have only one attached elastic network interface. The network interface should have a minimum of two assigned private IP addresses. However, for workloads that use Availability Groups, such as SQL Always On, you must include an additional IP address for each Availability Group. The primary IP address is used for accessing and managing the server, the Elastic Network Adapters (ENAs) 13 Microsoft SQL Server on Amazon EC2 User Guide secondary IP address is used as the cluster IP address, and each additional IP address is assigned to Availability Groups, as needed. Heartbeat network Some Microsoft documentation recommends using
sql-server-ec2-008
sql-server-ec2.pdf
8
cluster should have only one attached elastic network interface. The network interface should have a minimum of two assigned private IP addresses. However, for workloads that use Availability Groups, such as SQL Always On, you must include an additional IP address for each Availability Group. The primary IP address is used for accessing and managing the server, the Elastic Network Adapters (ENAs) 13 Microsoft SQL Server on Amazon EC2 User Guide secondary IP address is used as the cluster IP address, and each additional IP address is assigned to Availability Groups, as needed. Heartbeat network Some Microsoft documentation recommends using a dedicated heartbeat network. However, this recommendation is not applicable to EC2. With EC2, while you can assign and use a second elastic network interface for the heartbeat network, it uses the same infrastructure and shares bandwidth with the primary network interface. Therefore, traffic within the infrastructure cannot be prioritized, and cannot benefit from a dedicated network interface. Configure the network adapter in the OS The NIC in the OS can keep using DHCP as long as the DNS servers that are being retrieved from the DHCP Options Set allow for the nodes to resolve each other. You can set the NIC to be configured statically. When completed, you then manually configure only the primary IP address for the elastic network interface. Failover Clustering manages and assigns additional IP addresses, as needed. For certain instance types, you can increase the maximum transmission unit (MTU) on the network adapter to support Jumbo Frames. This configuration reduces fragmentation of packets wherever Jumbo Frames are supported. For more information, see Network maximum transmission unit (MTU) for your EC2 instance in the Amazon Elastic Compute Cloud User Guide. IPv6 Microsoft does not recommend disabling IPv6 in a Windows Cluster. While Failover Clustering works in an IPv4-only environment, Microsoft tests clusters with IPv6 enabled. See Failover Clustering and IPv6 in Windows Server 2012 R2 for details. Host record TTL for SQL Availability Group Listeners Set the host record TTL to 300 seconds instead of the default 20 minutes (1200 seconds). For legacy client comparability, set RegisterAllProvidersIP to 0 for SQL Availability Group Listeners. This is not required in all environments. These settings are important because some legacy client applications cannot use MultiSubnetFailover in their connection strings. See HostRecordTTL Setting for more information. When you change these settings, the Cluster Resource must be restarted. The Cluster Group for the listener stops when the Cluster Resource Heartbeat network 14 Microsoft SQL Server on Amazon EC2 User Guide is restarted, so it must be started. If you do not start the Cluster Group, the Availability Group remains offline in a RESOLVING state. The following are example PowerShell scripts for changing the TTL and RegisterAllProvidersIP settings. Get-ClusterResource yourListenerName | Set-ClusterParameter RegisterAllProvidersIP 0 Get-ClusterResource yourListenerName|Set-ClusterParameter HostRecordTTL 300 Stop-ClusterResource yourListenerName Start-ClusterResource yourListenerName Start-ClusterGroup yourListenerGroupName Logging The default logging level for the cluster log is 3. To increase the detail of log information, set the logging level to 5. See Set-ClusterLog for more information about the PowerShell cmdlet. Set-ClusterLog -Level 5 NetBIOS over TCP In Windows Server 2012 R2, you can increase the speed of the failover process by disabling NetBIOS over TCP. This feature was removed from Windows Server 2016. You should test this procedure if you are using earlier operating systems in your environment. For more information, see Speeding Up Failover Tips-n-Tricks. The following is an example PowerShell command to disable NetBIOS over TCP. Get-ClusterResource “Cluster IP Address” | Set-ClusterParameter EnableNetBIOS 0 NetFT Virtual Adapter For Windows Server versions earlier than 2016 and non-Hyper-V workloads, Microsoft recommends you enable the NetFT Virtual Adapter Performance Filter on the adapter in the OS. Logging 15 Microsoft SQL Server on Amazon EC2 User Guide When you enable the NetFT Virtual Adapter, internal cluster traffic is routed directly to the NetFT Virtual Adapter. For more information, see NetFT Virtual Adapter Performance Filter. You can enable NetFT Virtual Adapter by selecting the check box in the NIC properties, or by using the following PowerShell command. Get-NetAdapter | Set-NetAdapterBinding -ComponentID ms_netftflt -Enable $true Set possible owners The Failover Cluster Manager can be configured so that each IP address specified on the Cluster Core Resources and Availability Group resources can be brought online only on the node to which the IP belongs. When the Failover Cluster Manager is not configured for this and a failure occurs, there will be some delay in failover as the cluster attempts to bring up the IPs on nodes that do not recognize the address. For more information, see SQL Server Manages Preferred and Possible Owner Properties for AlwaysOn Availability Group/Role. Each resource in a cluster has a setting for Possible Owners. This setting tells the cluster which nodes are permitted to “online” a resource. Each node is running on a unique
sql-server-ec2-009
sql-server-ec2.pdf
9
Group resources can be brought online only on the node to which the IP belongs. When the Failover Cluster Manager is not configured for this and a failure occurs, there will be some delay in failover as the cluster attempts to bring up the IPs on nodes that do not recognize the address. For more information, see SQL Server Manages Preferred and Possible Owner Properties for AlwaysOn Availability Group/Role. Each resource in a cluster has a setting for Possible Owners. This setting tells the cluster which nodes are permitted to “online” a resource. Each node is running on a unique subnet in a VPC. Because EC2 cannot share IPs between instances, the IP resources in the cluster can be brought online only by specific nodes. By default, each IP address that is added to the cluster as a resource has every node listed as a Possible Owner. This does not result in failures. However, during expected and unexpected failures, you can see errors in the logs about conflicting IPs and failures to bring IPs online. These errors can be ignored. If you set the Possible Owner property, you can eliminate these errors entirely, and also prevent down time while the services are moved to another node. The following image shows an example of configuring an IP address so that it can only be brought online on the node to which the IP belongs: Set possible owners 16 Microsoft SQL Server on Amazon EC2 User Guide Tune the failover thresholds In Windows Server 2012 R2, the network thresholds for the failover heartbeat network default to high values. See Tuning Failover Cluster Network Thresholds for details. This potentially unreliable configuration, which applies to clusters with some distance between them, was addressed in Server 2016 with an increase in the number of heartbeats. It was discovered that clusters would fail over due to very brief transient network issues. The heartbeat network is maintained with UDP 3343, which is traditionally far less reliable than TCP and more prone to incomplete conversations. Although there are low-latency connections between AWS Availability Zones, there are still geographic separations with a number of "hops" separating resources. Within an Availability Zone, there may be some distance between clusters unless the customer is using Placement Groups or Tune the failover thresholds 17 Microsoft SQL Server on Amazon EC2 User Guide Dedicated Hosts. As a result, there is a higher possibility for heartbeat failure with UDP than with TCP-based heartbeats. The only time a cluster should fail over is when there is a legitimate outage, such as a service or node that experiences a hard failover, as opposed to a few UDP packets lost in transit. To ensure legitimate outages, we recommend that you adjust the thresholds to match, or even exceed, the settings for Server 2016 listed in Tuning Failover Cluster Network Thresholds. You can change the settings with the following PowerShell commands. (get-cluster).SameSubnetThreshold = 10 (get-cluster).CrossSubnetThreshold = 20 When you set these values, unexpected failovers should be dramatically reduced. You can fine tune these settings by increasing the delays between heartbeats. However, we recommend that you send the heartbeats more frequently with greater thresholds. Setting these thresholds even higher ensures that failovers occur only for hard failover scenarios, with longer delays before failing over. You must decide how much down time is acceptable for your applications. After increasing the SameSubnetThreshold or CrossSubnetThreshold, we recommend that you increase the RouteHistoryLength to double the higher of the two values. This ensures that there is sufficient logging for troubleshooting. You can set the RouteHistoryLength with the following PowerShell command. (Get-Cluster).RouteHistoryLength = 20 Witness importance and Dynamic Quorum Architecture There is a difference between Disk Witness and File Share Witness. Disk Witness keeps a backup of the cluster database while File Share Witness does not. Both add a vote to the cluster. You can use Disk Witness if you use iSCSI-based storage. For more about witness options, see File Share witness vs Disk witness for local clusters. Troubleshoot If you experience unexpected failovers, first make sure that you are not experiencing networking, service, or infrastructure issues. Witness importance and Dynamic Quorum Architecture 18 Microsoft SQL Server on Amazon EC2 User Guide 1. Check that your nodes are not experiencing network-related issues. 2. Check driver updates. If you are using outdated drivers on your instance, you should update them. Updating your drivers might address bugs and stability issues that might be present in your currently installed version. 3. Check for any possible resource bottlenecks that could cause an instance to become unresponsive, such as CPU and disk I/O. If the node cannot service requests, it might appear to be down by the cluster service. Troubleshoot 19 Microsoft SQL Server on Amazon EC2 User Guide Set up Microsoft SQL Server on Amazon EC2 Describes the
sql-server-ec2-010
sql-server-ec2.pdf
10
that your nodes are not experiencing network-related issues. 2. Check driver updates. If you are using outdated drivers on your instance, you should update them. Updating your drivers might address bugs and stability issues that might be present in your currently installed version. 3. Check for any possible resource bottlenecks that could cause an instance to become unresponsive, such as CPU and disk I/O. If the node cannot service requests, it might appear to be down by the cluster service. Troubleshoot 19 Microsoft SQL Server on Amazon EC2 User Guide Set up Microsoft SQL Server on Amazon EC2 Describes the prerequisites, permissions, and configurations that you should consider when preparing to use Microsoft SQL Server on Amazon EC2 instances for your SQL Server workloads. Topics for setting up SQL Server on Amazon EC2 • Prerequisites for using SQL Server on Amazon EC2 • Permissions required to use SQL Server on Amazon EC2 Prerequisites for using SQL Server on Amazon EC2 Complete the tasks in this section to start using SQL Server on Amazon EC2 instances for the first time: 1. Sign up for an AWS account 2. Create a user with administrative access 3. Create a key pair 4. Create a security group Sign up for an AWS account If you do not have an AWS account, complete the following steps to create one. To sign up for an AWS account 1. Open https://portal.aws.amazon.com/billing/signup. 2. Follow the online instructions. Part of the sign-up procedure involves receiving a phone call and entering a verification code on the phone keypad. When you sign up for an AWS account, an AWS account root user is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to perform tasks that require root user access. Prerequisites 20 Microsoft SQL Server on Amazon EC2 User Guide AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to https://aws.amazon.com/ and choosing My Account. Create a user with administrative access After you sign up for an AWS account, secure your AWS account root user, enable AWS IAM Identity Center, and create an administrative user so that you don't use the root user for everyday tasks. Secure your AWS account root user 1. Sign in to the AWS Management Console as the account owner by choosing Root user and entering your AWS account email address. On the next page, enter your password. For help signing in by using root user, see Signing in as the root user in the AWS Sign-In User Guide. 2. Turn on multi-factor authentication (MFA) for your root user. For instructions, see Enable a virtual MFA device for your AWS account root user (console) in the IAM User Guide. Create a user with administrative access 1. Enable IAM Identity Center. For instructions, see Enabling AWS IAM Identity Center in the AWS IAM Identity Center User Guide. 2. In IAM Identity Center, grant administrative access to a user. For a tutorial about using the IAM Identity Center directory as your identity source, see Configure user access with the default IAM Identity Center directory in the AWS IAM Identity Center User Guide. Sign in as the user with administrative access • To sign in with your IAM Identity Center user, use the sign-in URL that was sent to your email address when you created the IAM Identity Center user. Create a user with administrative access 21 Microsoft SQL Server on Amazon EC2 User Guide For help signing in using an IAM Identity Center user, see Signing in to the AWS access portal in the AWS Sign-In User Guide. Assign access to additional users 1. In IAM Identity Center, create a permission set that follows the best practice of applying least- privilege permissions. For instructions, see Create a permission set in the AWS IAM Identity Center User Guide. 2. Assign users to a group, and then assign single sign-on access to the group. For instructions, see Add groups in the AWS IAM Identity Center User Guide. Create a key pair AWS uses public-key cryptography to secure the login information for your instance. You specify the name of the key pair when you launch your instance, then provide the private key to obtain the administrator password for your Windows instance so you can log in using RDP. If you haven't created a key pair already, you can create one by using the Amazon EC2 console. Note that if you plan to launch instances in multiple Regions, you'll need to create a key pair in each Region. For more information about Regions, see Regions and Zones in the User Guide
sql-server-ec2-011
sql-server-ec2.pdf
11
key pair AWS uses public-key cryptography to secure the login information for your instance. You specify the name of the key pair when you launch your instance, then provide the private key to obtain the administrator password for your Windows instance so you can log in using RDP. If you haven't created a key pair already, you can create one by using the Amazon EC2 console. Note that if you plan to launch instances in multiple Regions, you'll need to create a key pair in each Region. For more information about Regions, see Regions and Zones in the User Guide for Windows Instances. To create your key pair 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Key Pairs. 3. Choose Create key pair. 4. 5. For Name, enter a descriptive name for the key pair. Amazon EC2 associates the public key with the name that you specify as the key name. A key name can include up to 255 ASCII characters. It can’t include leading or trailing spaces. For Key pair type, choose either RSA or ED25519. Note that ED25519 keys are not supported for Windows instances. Create a key pair 22 Microsoft SQL Server on Amazon EC2 User Guide 6. For Private key file format, choose the format in which to save the private key. To save the private key in a format that can be used with OpenSSH, choose pem. To save the private key in a format that can be used with PuTTY, choose ppk. If you chose ED25519 in the previous step, the Private key file format options do not appear, and the private key format defaults to pem. 7. Choose Create key pair. 8. The private key file is automatically downloaded by your browser. The base file name is the name you specified as the name of your key pair, and the file name extension is determined by the file format you chose. Save the private key file in a safe place. Important This is the only chance for you to save the private key file. For more information, see Amazon EC2 key pairs and Windows instances in the User Guide for Windows Instances. Create a security group Security groups act as a firewall for associated instances, controlling both inbound and outbound traffic at the instance level. You must add rules to a security group that enable you to connect to your instance from your IP address using RDP. You can also add rules that allow inbound and outbound HTTP and HTTPS access from anywhere. Note that if you plan to launch instances in multiple Regions, you'll need to create a security group in each Region. For more information about Regions, see Regions and Zones in the User Guide for Windows Instances. Prerequisites You'll need the public IPv4 address of your local computer. The security group editor in the Amazon EC2 console can automatically detect the public IPv4 address for you. Alternatively, you can use the search phrase "what is my IP address" in an Internet browser, or use the following service: Check IP. If you are connecting through an Internet service provider (ISP) or from behind a firewall without a static IP address, you need to find out the range of IP addresses used by client computers. You can create a custom security group using one of the following methods. Create a security group 23 Microsoft SQL Server on Amazon EC2 New Amazon EC2 console To create a security group with least privilege User Guide 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. From the top navigation bar, select a Region for the security group. Security groups are specific to a Region, so you should select the same Region in which you created your key pair. 3. In the left navigation pane, choose Security Groups. 4. Choose Create security group. 5. For Basic details, do the following: a. Enter a name for the new security group and a description. Use a name that is easy for you to remember, such as your user name, followed by _SG_, plus the Region name. For example, me_SG_uswest2. b. In the VPC list, select your default VPC for the Region. 6. For Inbound rules, create rules that allow specific traffic to reach your instance. For example, use the following rules for a web server that accepts HTTP and HTTPS traffic. For more examples, see Security group rules for different use cases in the User Guide for Windows Instances. a. Choose Add rule. For Type, choose HTTP. For Source, choose Anywhere. b. Choose Add rule. For Type, choose HTTPS. For Source, choose Anywhere. c. Choose Add rule. For Type, choose RDP. For Source, do one of the following: • Choose My IP to automatically add the public IPv4 address of your local
sql-server-ec2-012
sql-server-ec2.pdf
12
For Inbound rules, create rules that allow specific traffic to reach your instance. For example, use the following rules for a web server that accepts HTTP and HTTPS traffic. For more examples, see Security group rules for different use cases in the User Guide for Windows Instances. a. Choose Add rule. For Type, choose HTTP. For Source, choose Anywhere. b. Choose Add rule. For Type, choose HTTPS. For Source, choose Anywhere. c. Choose Add rule. For Type, choose RDP. For Source, do one of the following: • Choose My IP to automatically add the public IPv4 address of your local computer. • Choose Custom and specify the public IPv4 address of your computer or network in CIDR notation. To specify an individual IP address in CIDR notation, add the routing suffix /32, for example, 203.0.113.25/32. If your company or your router allocates addresses from a range, specify the entire range, such as 203.0.113.0/24. Warning For security reasons, do not choose Anywhere for Source with a rule for RDP. This would allow access to your instance from all IP addresses on the internet. Create a security group 24 Microsoft SQL Server on Amazon EC2 User Guide This is acceptable for a short time in a test environment, but it is unsafe for production environments. 7. For Outbound rules, keep the default rule, which allows all outbound traffic. 8. Choose Create security group. Old Amazon EC2 console To create a security group with least privilege 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the left navigation pane, choose Security Groups. 3. Choose Create Security Group. 4. Enter a name for the new security group and a description. Use a name that is easy for you to remember, such as your user name, followed by _SG_, plus the Region name. For example, me_SG_uswest2. 5. In the VPC list, select your default VPC for the Region. 6. On the Inbound rules tab, create the following rules (choose Add rule for each new rule): • Choose HTTP from the Type list, and make sure that Source is set to Anywhere (0.0.0.0/0). • Choose HTTPS from the Type list, and make sure that Source is set to Anywhere (0.0.0.0/0). • Choose RDP from the Type list. In the Source box, choose My IP to automatically populate the field with the public IPv4 address of your local computer. Alternatively, choose Custom and specify the public IPv4 address of your computer or network in CIDR notation. To specify an individual IP address in CIDR notation, add the routing suffix /32, for example, 203.0.113.25/32. If your company allocates addresses from a range, specify the entire range, such as 203.0.113.0/24. Warning For security reasons, do not allow RDP access from all IP addresses to your instance. This is acceptable for a short time in a test environment, but it is unsafe for production environments. Create a security group 25 Microsoft SQL Server on Amazon EC2 User Guide 7. On the Outbound rules tab, keep the default rule, which allows all outbound traffic. 8. Choose Create security group. Command line To create a security group with least privilege Use one of the following commands: • create-security-group (AWS CLI) • New-EC2SecurityGroup (AWS Tools for Windows PowerShell) For more information, see Amazon EC2 security groups for Windows instances in the Amazon EC2 User Guide. Permissions required to use SQL Server on Amazon EC2 For information about the permissions required to create or modify Amazon EC2 resources, or to perform tasks using the Amazon EC2 API, see IAM policies for Amazon EC2 in the User Guide for Windows Instances. Permissions 26 Microsoft SQL Server on Amazon EC2 User Guide Understand licensing options and considerations for Microsoft SQL Server on Amazon EC2 There are two ways in which you can license Microsoft SQL Server on Amazon EC2 on the AWS Cloud. You acquire your own existing SQL Server licenses, or those which are provided by AWS. The most cost-effective license strategy for your workload will depend on multiple factors. For more information on comparing the costs of SQL Server editions, see Compare SQL Server editions on the AWS Prescriptive Guidance website. Topics • Licensing options • Licensing considerations Licensing options You can launch Amazon Elastic Compute Cloud (Amazon EC2) instances with Microsoft SQL Server licenses included from AWS, or you can bring your own SQL Server licenses for use on AWS. You can perform a license type conversion for SQL Server in certain configurations if your needs change. For the most license flexibility, you can import your VM into AWS. For more information, see Eligible license types for license type conversion in the AWS License Manager User Guide. Licensing options topics • License-included • BYOL License-included Windows Server with currently supported versions of Microsoft SQL Server AMIs are available from AWS in a
sql-server-ec2-013
sql-server-ec2.pdf
13
Amazon Elastic Compute Cloud (Amazon EC2) instances with Microsoft SQL Server licenses included from AWS, or you can bring your own SQL Server licenses for use on AWS. You can perform a license type conversion for SQL Server in certain configurations if your needs change. For the most license flexibility, you can import your VM into AWS. For more information, see Eligible license types for license type conversion in the AWS License Manager User Guide. Licensing options topics • License-included • BYOL License-included Windows Server with currently supported versions of Microsoft SQL Server AMIs are available from AWS in a variety of combinations. AWS provides these AMIs with SQL Server software and operating system updates already installed. When you purchase an Amazon EC2 instance with a Windows Server AMI, licensing costs and compliance are handled for you. For more information, see Find a SQL Server license-included AMI. Licensing options 27 Microsoft SQL Server on Amazon EC2 User Guide Amazon EC2 offers a variety of instance types and sizes that you can configure for your target workload. Amazon EC2 AMIs with Windows Server require no Client Access Licenses (CALs). They also include two Microsoft Remote Desktop Services licenses for administrative purposes. For SQL Server license-included AMIs, use the installation and setup media included in C: \SQLServerSetup to perform in-place SQL Server version upgrades, make changes to the default installation, add new features, or install additional named instances. BYOL When you launch a SQL Server instance from an imported AMI, you can bring your existing licenses with the Bring Your Own License model (BYOL), and let AWS manage them to ensure compliance with licensing rules that you set. To import your own licensed image, you can use a service such as VM Import/Export or AWS Application Migration Service. After you import your licensed image, and it is available as a private AMI in your AWS account on the Amazon EC2 console, you can use the AWS License Manager service to create a license configuration. After you create the license configuration, you must associate the AMI that contains your licensed operating system image with the configuration. Then, you must create a host resource group and associate it with the license configuration. After you associate your host resource group with the configuration, License Manager automatically manages your hosts when you launch instances into a host resource group, and ensures that you do not exceed your configured license count limits. For more information, see the Getting started section of the License Manager User Guide. You can also bring your own SQL Server licenses with Active Software Assurance to default (shared) tenant Amazon EC2 through Microsoft License Mobility through Software Assurance. For information about how to sign up for Microsoft License Mobility, see License Mobility. Licensing considerations There are many considerations for cost effectively licensing your Microsoft SQL Server on Amazon EC2 workload. Your use case, and existing license agreements, will determine whether to bring your own license to AWS with the Bring Your Own License model (BYOL) or to use license included AMIs from AWS. The following topics should help determine which approach you might take. For more information, see Licensing - SQL Server on the Amazon Web Services and Microsoft Frequently Asked Questions page. Licensing considerations topics • Choose a SQL Server edition BYOL 28 Microsoft SQL Server on Amazon EC2 User Guide • Purchase SQL Server from AWS • Use BYOL for SQL Server on AWS • Quantify the required SQL Server licenses for BYOL • License Mobility with SQL Server • Track BYOL license consumption • SQL Server client access licenses (CALs) • Licensing for passive failover Choose a SQL Server edition The edition of SQL Server that is used will determine the supported features your implementation will have available. For example, the edition determines the maximum compute capacity used by a single instance of the SQL Server Database Engine, and the high availability options you might implement. For a comparison of SQL Server editions and supported features, see Editions and supported features of SQL Server 2022 in the Microsoft documentation. Purchase SQL Server from AWS You can utilize Microsoft SQL Server licenses included from AWS. You can choose any of the following editions for your use on Amazon EC2 instances. • SQL Server Web • SQL Server Standard • SQL Server Enterprise Note • SQL Server Express AMIs are available for use from AWS. This free edition of SQL Server doesn’t incur additional charges as there is no licensing fee. • SQL Server Developer edition is eligible for use in non-production, development, and test workloads. Once downloaded from Microsoft, you can bring and install SQL Server Developer edition on Amazon EC2 instances in the AWS Cloud. Dedicated infrastructure is not required for SQL Server Developer edition. For more information, see https://
sql-server-ec2-014
sql-server-ec2.pdf
14
following editions for your use on Amazon EC2 instances. • SQL Server Web • SQL Server Standard • SQL Server Enterprise Note • SQL Server Express AMIs are available for use from AWS. This free edition of SQL Server doesn’t incur additional charges as there is no licensing fee. • SQL Server Developer edition is eligible for use in non-production, development, and test workloads. Once downloaded from Microsoft, you can bring and install SQL Server Developer edition on Amazon EC2 instances in the AWS Cloud. Dedicated infrastructure is not required for SQL Server Developer edition. For more information, see https:// www.microsoft.com/en-us/sql-server/sql-server-downloads. Choose a SQL Server edition 29 Microsoft SQL Server on Amazon EC2 User Guide Use BYOL for SQL Server on AWS You can use BYOL licenses for SQL Server on AWS. The requirements differ depending on if the licenses have active Software Assurance. SQL Server licenses with active Software Assurance You can bring your SQL Server licenses with active Software Assurance to default (shared) tenant Amazon EC2 through License Mobility benefits. Microsoft requires that you complete and send a License Mobility verification form which can be downloaded here. For more information, see License Mobility. SQL Server licenses without active Software Assurance SQL Server licenses without Software Assurance can be deployed on Amazon Elastic Compute Cloud Dedicated Hosts if the licenses are purchased prior to 10/1/2019 or added as a true-up under an active Enterprise Enrollment that was effective prior to 10/1/2019. In these specific BYOL scenarios, the licenses can only be upgraded to versions that were available prior to 10/1/2019. For more information, see Dedicated Hosts in the Amazon EC2 User Guide, and the Amazon EC2 Dedicated Hosts FAQs. Quantify the required SQL Server licenses for BYOL If you are licensing SQL Server under Microsoft License Mobility through Software Assurance, the number of licenses required varies based on the instance type, version of SQL Server, and the Microsoft licensing model you choose. For assistance with virtual core licensing calculations under the Microsoft Product Terms based on the instance type, see SQL License Mobility. If you are using Dedicated Hosts, Amazon EC2 provides you with the number of physical cores installed on the Dedicated Host. Using this information, you can calculate the number of SQL Server licenses that you need to bring in. For more information, see Amazon EC2 Dedicated Hosts Pricing and the SQL Server 2022 licensing guide. License Mobility with SQL Server SQL Server licenses with active Software Assurance are eligible for Microsoft License Mobility and can be deployed on default or dedicated tenant Amazon EC2. For more information on bringing SQL Server licenses with active Software Assurance to default tenant EC2, see Microsoft License Mobility. Use BYOL for SQL Server on AWS 30 Microsoft SQL Server on Amazon EC2 User Guide It is also possible to bring SQL Server licenses without active Software Assurance to EC2 Dedicated Hosts. To be eligible, the licenses must be purchased prior to October 1, 2019 or added as a true-up under an active Enterprise Enrollment that was effective prior to October 1, 2019. For additional FAQs about Dedicated Hosts, see the Dedicated Hosts section of the Amazon Web Services and Microsoft FAQ. Track BYOL license consumption You can use AWS License Manager to manage your software licenses for SQL Server. With License Manager, you can create license configurations, take inventory of your license-consuming resources, associate licenses with resources, and track inventory and compliance. For more information, see What is AWS License Manager? in the AWS License Manager User Guide. SQL Server client access licenses (CALs) When you are using SQL Server on Amazon EC2, license included instances do not require client access licenses (CALs) for SQL Server. An unlimited number of end users can access SQL Server on a license-included instance. When you bring your own SQL Server licenses to Amazon EC2 through Microsoft License Mobility or BYOL, you must continue to follow the licensing rules in place on-premises. If you purchased SQL Server under the Server/CAL model, you still require CALs to meet Microsoft licensing requirements, but these CALs would remain on-premises and enable end user access SQL Server running on AWS. Licensing for passive failover There are various factors to consider when licensing passive failover for SQL Server. The information in this section pertains only to the SQL Server licenses and not the Windows Server licenses. In all cases, you must license Windows Server. Using instances that include the license for SQL Server When you purchase SQL Server license included instances on EC2, you must license passive failover instances. Bringing SQL Server licenses with active Software Assurance to default tenant Amazon EC2 When you bring SQL Server 2014 and later versions with Software Assurance to default tenant EC2, you must license the virtual cores (vCPUs) on the active instance.
sql-server-ec2-015
sql-server-ec2.pdf
15
to consider when licensing passive failover for SQL Server. The information in this section pertains only to the SQL Server licenses and not the Windows Server licenses. In all cases, you must license Windows Server. Using instances that include the license for SQL Server When you purchase SQL Server license included instances on EC2, you must license passive failover instances. Bringing SQL Server licenses with active Software Assurance to default tenant Amazon EC2 When you bring SQL Server 2014 and later versions with Software Assurance to default tenant EC2, you must license the virtual cores (vCPUs) on the active instance. In return, Software Track BYOL license consumption 31 Microsoft SQL Server on Amazon EC2 User Guide Assurance permits one passive instance (equal or lesser size) where SQL Server licensing is not required. Bringing SQL Server to Amazon EC2 Dedicated Instances SQL Server 2014 and later versions require Software Assurance for SQL Server passive failover benefits on dedicated infrastructure. When you bring SQL Server with Software Assurance, you must license the cores on the active instance/host and are permitted one passive instance/host (equal or lesser size) where SQL Server licensing is not required. SQL Server 2008 - SQL Server 2012R2 are eligible for passive failover on an Amazon EC2 Dedicated Hosts infrastructure without active Software Assurance. In these scenarios, you will license the active instance/host, and it will be permitted one passive instance/host of equal or lesser size where SQL Server licensing is not required. There are specific BYOL scenarios that do not require Microsoft License Mobility through Software Assurance. An Amazon EC2 Dedicated Hosts infrastructure is always required in these scenarios. To be eligible, the licenses must be purchased prior to October 1, 2019 or added as a true-up under an active Enterprise Enrollment that was effective prior to October 1, 2019. In these specific BYOL scenarios, the licenses can only be upgraded to versions that were available prior to October 1, 2019. Licensing for passive failover 32 Microsoft SQL Server on Amazon EC2 User Guide Find a SQL Server license-included AMI This topic describes how you can find SQL Server license-included AMIs using the Amazon EC2 console, the AWS Tools for PowerShell, the AWS CLI, or by searching the AWS Marketplace. For SQL Server license-included AMIs, use the installation and setup media included in C: \SQLServerSetup to make changes to the default installation, add new features, or install additional named instances. As you select a SQL Server license-included AMI, consider the following requirements you might have for the instances that you'll launch: • The AWS Region • The operating system • The architecture: 64-bit (x86_64) • The root device type: Amazon EBS-backed (EBS) • The provider (for example, Amazon Web Services) • Additional software (for example, SQL Server) Note To view changes to each release of the AWS Windows AMIs, including SQL Server updates, see the AWS Windows AMI version history in the Amazon EC2 User Guide. Methods to find a SQL Server license-included AMI AWS Marketplace To view a list of SQL Server AMIs available from AWS in AWS Marketplace, see Windows AMIs. Console You can find SQL Server license-included AMIs using the Amazon EC2 console. You can select from the list of AMIs when you use the launch instance wizard to launch an instance, or you can search through all available AMIs using the Images page. AMI IDs are unique to each AWS Region. Methods to find a SQL Server license-included AMI 33 Microsoft SQL Server on Amazon EC2 User Guide To find a SQL Server license-included AMI using the launch instance wizard 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. From the navigation bar, select the Region in which to launch your instances. You can select any Region that's available to you, regardless of your location. 3. From the console dashboard, choose Launch instances. 4. Under Application and OS Images (Amazon Machine Image), enter SQL in the search bar and choose Enter. You will be taken to the AMIs page, where you can browse and choose from AMIs with SQL Server included. You can choose from AMIs under the Quickstart AMIs, My AMIs, AWS Marketplace AMIs, and the Community AMIs tabs. You can filter by cost, operating system, and architecture. 5. To launch an instance from this AMI, select it and then choose Launch instance. For more information about launching an instance using the console, see Launch an instance using the new launch instance wizard. If you're not ready to launch the instance now, take note of the AMI ID for later. To find a SQL Server AMI using the AMIs page 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. From the navigation bar, select the Region in which to launch your instances. You can select 3. 4. 5. any Region that's available to
sql-server-ec2-016
sql-server-ec2.pdf
16
cost, operating system, and architecture. 5. To launch an instance from this AMI, select it and then choose Launch instance. For more information about launching an instance using the console, see Launch an instance using the new launch instance wizard. If you're not ready to launch the instance now, take note of the AMI ID for later. To find a SQL Server AMI using the AMIs page 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. From the navigation bar, select the Region in which to launch your instances. You can select 3. 4. 5. any Region that's available to you, regardless of your location. In the navigation pane, choose AMI Catalog. Enter SQL in the search bar and choose Enter. You can choose from SQL Server license- included AMIs under the Quickstart AMIs, My AMIs, AWS Marketplace AMIs, and the Community AMIs tabs. You can filter by cost, operating system, and architecture. To launch an instance from this AMI, select it and then choose Launch instance . For more information about launching an instance using the console, see Launching your instance from an AMI. If you're not ready to launch the instance now, take note of the AMI ID for later. PowerShell You can use cmdlets for Amazon EC2 to list only the Windows AMIs that match your requirements. After locating an AMI that matches your requirements, take note of its ID so Methods to find a SQL Server license-included AMI 34 Microsoft SQL Server on Amazon EC2 User Guide that you can use it to launch instances. For more information, see Launch an Instance Using Windows PowerShell in the AWS Tools for Windows PowerShell User Guide. To list the latest SQL Server license-included AMIs provided by Amazon, you can use the Get- SSMLatestEC2Image cmdlet. The following command lists the latest Windows AMIs with SQL in their image name: Get-SSMLatestEC2Image -Path ami-windows-latest -ImageName *SQL* To list SQL Server license-included AMIs using commands that match specific criteria, you can use the Get-EC2Image cmdlet in addition to filters. The following commands filter for AMIs owned by you, or Amazon, with SQL in their name: $name_values = New-Object 'collections.generic.list[string]' $name_values.add("*SQL*") $filter_name = New-Object Amazon.EC2.Model.Filter -Property @{Name = "name"; Values = $name_values} Get-EC2Image -Owner amazon, self -Filter $filter_name For more information and examples, see Find an AMI Using Windows PowerShell in the AWS Tools for Windows PowerShell User Guide. AWS CLI You can use AWS CLI commands for Amazon EC2 to list only the SQL Server license-included AMIs that match your requirements. After locating an AMI that matches your requirements, take note of its ID so that you can use it to launch instances. For more information, see Launching an Instance Using the AWS CLI in the AWS Command Line Interface User Guide. The describe-images command supports filtering parameters. For example, use the --owners parameter with amazon to display public AMIs owned by Amazon or self to list AMIs you own. You can specify multiple values for the --owners parameter as in the following example: aws ec2 describe-images --owners self amazon You can add the following filter to the previous command to display only SQL Server license- included AMIs: --filters "Name=name,Values=*SQL*" Methods to find a SQL Server license-included AMI 35 Microsoft SQL Server on Amazon EC2 User Guide You can use the following filter with the command to display only AMIs backed by Amazon EBS: --filters "Name=root-device-type,Values=ebs" You can combine multiple filters together. For example, this command will list all AMIs owned by you or Amazon with SQL in the AMI name and the --root-device-type parameter as ebs: aws ec2 describe-images --owners self amazon --filters "Name=name,Values=*SQL*" "Name=root-device-type,Values=ebs" Note Omitting the --owners flag from the describe-images command will return all images for which you have launch permissions, regardless of ownership. Methods to find a SQL Server license-included AMI 36 Microsoft SQL Server on Amazon EC2 User Guide Deploy SQL Server on Amazon EC2 To launch Microsoft SQL Server using Amazon Elastic Compute Cloud (Amazon EC2) instances with Windows Server, perform the following steps according to your use case. New SQL environment deployments are classified under three categories: • SQL Server standalone • SQL Server Failover Cluster Instances (FCI) • SQL Server Always On availability groups (AG) Considerations Before you launch SQL Server on your instance, consider the following: • If you use an AWS provided AMI, you must initially manage SQL Server as the local administrator. For more information, see Connect to SQL Server on Amazon EC2. • If you use an instance type that provides an instance store, we recommend that you place tempdb on an instance store volume. This can improve performance and decrease costs. For more information, see Place tempdb in an instance store. • The built-in availability form of clustering in Windows Server is activated by a feature named Failover
sql-server-ec2-017
sql-server-ec2.pdf
17
groups (AG) Considerations Before you launch SQL Server on your instance, consider the following: • If you use an AWS provided AMI, you must initially manage SQL Server as the local administrator. For more information, see Connect to SQL Server on Amazon EC2. • If you use an instance type that provides an instance store, we recommend that you place tempdb on an instance store volume. This can improve performance and decrease costs. For more information, see Place tempdb in an instance store. • The built-in availability form of clustering in Windows Server is activated by a feature named Failover Clustering. This feature allows you to build a Windows Server Failover Cluster (WSFC) to use with an availability group or failover cluster instances (FCI). • Always On is an umbrella term for the availability features in SQL Server, and the term covers both availability groups and FCIs. Always On isn't the name of the Always On availability group (AG) feature. • The major difference between FCI and AG is that all FCIs require some sort of shared storage, even if it's provided through networking. The FCI's resources can be run and owned by one node at any given time. AG doesn't require that shared storage is also highly available. It's a best practice to have replicas that are local in one data center for high availability, and remote ones in other data centers for disaster recovery, each with separate storage. • An availability group also has another component called the listener. The listener allows applications and end users to connect without needing to know which SQL Server instance is hosting the primary replica. Each availability group has its own listener. Considerations 37 Microsoft SQL Server on Amazon EC2 Deployment options User Guide Use one of the following options to deploy SQL Server on Amazon EC2. Deploy SQL Server on Amazon EC2 with AWS Launch Wizard AWS Launch Wizard is a service that guides you through the sizing, configuration, and deployment of enterprise applications following AWS Cloud best practices. AWS Launch Wizard for SQL Server supports both high availability and single instance deployments according to AWS and SQL Server best practices. For more information, see the AWS Launch Wizard for SQL Server User Guide. Always On availability groups (AG) Deploy your SQL Server Always On availability groups with primary and secondary replicas for database level protection. Each replica is hosted by a SQL Server instance with its own local storage. Always On Failover Cluster Instances (SQL FCI) Deploy SQL Server Always On using Failover Cluster Instances (FCI) for instance-level protection. A single SQL Server instance is installed across Windows Server Failover Clustering (WSFC) nodes to ensure high availability and storage sharing. Launch Wizard uses Amazon FSx to provide the following shared storage options required for SQL FCI deployments: • Amazon FSx for NetApp ONTAP using Microsoft iSCSI endpoint • Amazon FSx for Windows File Server using SMB 3.0 continuously available Windows file share For more information on how to deploy SQL Server with Launch Wizard, see Deploy an application with AWS Launch Wizard for SQL Server on Windows in the AWS Launch Wizard User Guide. Deploy SQL Server standalone For a SQL Server standalone deployment, you can use one of the license-include AMIs provided by AWS or by using your own licensed media. For a list of SQL Server AMIs provided by AWS, see Windows AMIs. For more information on licensing options, see Understand licensing options and considerations for Microsoft SQL Server on Amazon EC2. Deployment options 38 Microsoft SQL Server on Amazon EC2 User Guide Deploy SQL Server failover cluster instances (FCIs) Failover cluster instances (FCIs) provide availability for the entire installation of SQL Server known as an instance. Everything that is included in the instance, such as databases, SQL Server Agent jobs, and linked servers, move to a different server when the underlying server fails. You can use AWS Launch Wizard to deploy SQL Server FCIs in the AWS Cloud. Launch Wizard identifies the AWS resources to automatically provision the SQL Server databases based on your use case. For more information, see Get started with AWS Launch Wizard for SQL Server. You can reference the following AWS blogs to manually deploy SQL Server FCIs: • (Amazon FSx) Deploy a SQL Server FCI using SMB 3.0 Continuously Available File Shares (CAFS) as shared storage • (Amazon FSx) Deploy a SQL Server FCI using Microsoft iSCSI Initiator as shared storage • (Amazon EBS) Deploy SQL Server FCI using Amazon EBS Multi-Attach with Persistent Reservations (MAPR) Deploy SQL Server Always On availability groups (AG) Always on availability groups provide high availability and disaster recovery of user databases through data replication. Availability groups can also distribute read operations amongst member nodes. You can use AWS Launch Wizard to deploy a SQL Server Always
sql-server-ec2-018
sql-server-ec2.pdf
18
manually deploy SQL Server FCIs: • (Amazon FSx) Deploy a SQL Server FCI using SMB 3.0 Continuously Available File Shares (CAFS) as shared storage • (Amazon FSx) Deploy a SQL Server FCI using Microsoft iSCSI Initiator as shared storage • (Amazon EBS) Deploy SQL Server FCI using Amazon EBS Multi-Attach with Persistent Reservations (MAPR) Deploy SQL Server Always On availability groups (AG) Always on availability groups provide high availability and disaster recovery of user databases through data replication. Availability groups can also distribute read operations amongst member nodes. You can use AWS Launch Wizard to deploy a SQL Server Always On availability group in the AWS Cloud. Launch Wizard identifies the AWS resources to automatically provision the SQL Server databases based on your use case. For more information, see Get started with AWS Launch Wizard for SQL Server. To manually deploy a SQL Server Always On availability group, perform the following steps: Prerequisites Before you manually deploy a SQL Server Always On availability group, you must perform the following prerequisites. • Launch two Amazon EC2 instances with Windows Server 2016 or later and SQL Server 2016 or later Enterprise edition across two Availability Zones within an Amazon VPC. If the deployment is for testing purposes only, you can consider using SQL Server Developer edition. Deployment options 39 Microsoft SQL Server on Amazon EC2 User Guide • Configure secondary Amazon EBS volumes to host SQL Server Master Data File (MDF), Log Data File (LDF), and SQL Backup files (.bak). For more information on the volume types that you can use, see Amazon EBS volume types in the Amazon Elastic Compute Cloud User Guide. • Deploy the cluster nodes in private subnets. You can then use Remote Desktop Protocol (RDP) to connect from a jump server to the cluster node instances. • Configure inbound security group rules and Windows firewall exceptions to allow the nodes to communicate in a restrictive environment. • Open all necessary ports for Active Directory domain controllers so that the SQL nodes and witness can join the domain and authenticate against Active Directory. For more information, see Active Directory and Active Directory Domain Services Port Requirements in the Microsoft documentation. • Join the nodes to the domain before you create the Windows failover cluster. Ensure that you are logged in with domain credentials before you create and configure the cluster. • Run the SQL Database instances with an Active Directory service account. • Create a SQL login with sysadmin permissions using Windows domain authentication. Consult with your database administrator for details. For more information, see Create a login using SSMS for SQL Server in the Microsoft documentation. • Properly configure the SQL browser for SQL Server named instances. Configure the secondary IPs for each cluster node elastic network interface Two secondary IP addresses are required for each cluster node elastic network interface. Note If you do not plan to deploy a SQL Group Listener, add only one secondary IP address for each cluster node elastic network interface. 1. Navigate to the Amazon EC2 console and choose the AWS Region where you want to host your Always On cluster. 2. Choose Instances from the left navigation pane, and then select your Amazon EC2 cluster instance. 3. Choose the Networking tab. Deployment options 40 Microsoft SQL Server on Amazon EC2 User Guide 4. Under Network interfaces, select the network interface and then choose Actions > Manage IP addresses. 5. Choose the network interface Id to open the expandable section, and then choose Assign new IP address. You can enter a specific IP address or keep the default entry as Auto-assign. Repeat this step to add a second new IP address. 6. Choose Save > Confirm. 7. Repeat steps 1 through 7 for the other Amazon EC2 instance that will be included in the cluster. Create a two-node Windows cluster Perform the following steps to create a two-node Windows cluster. 1. Connect to your Amazon EC2 instance with RDP, using a domain account with local administrator permissions on both nodes. 2. On the Windows Start menu, open Control Panel, and then choose Network and Internet > Network and Sharing Center. 3. Choose Change adapter settings from the left navigation pane. 4. Choose your network connection, and then choose Change settings of this connection. 5. Choose Internet Protocol Version 4 TCP/IPV4), and then choose Properties. 6. Choose Advanced. 7. Under the DNS tab, choose Append primary and connection specific DNS suffixes. 8. Choose OK > OK > Close. 9. Repeat steps 1 through 8 for the other Amazon EC2 instance to include in the cluster. 10. On each instance, install the cluster feature on the nodes from the Server Manager, or run the following Windows PowerShell command: Install-WindowsFeature -Name Failover-Clustering -IncludeManagementTools 11. Open the command line as an administrator and enter cluadmin.msc
sql-server-ec2-019
sql-server-ec2.pdf
19
Choose your network connection, and then choose Change settings of this connection. 5. Choose Internet Protocol Version 4 TCP/IPV4), and then choose Properties. 6. Choose Advanced. 7. Under the DNS tab, choose Append primary and connection specific DNS suffixes. 8. Choose OK > OK > Close. 9. Repeat steps 1 through 8 for the other Amazon EC2 instance to include in the cluster. 10. On each instance, install the cluster feature on the nodes from the Server Manager, or run the following Windows PowerShell command: Install-WindowsFeature -Name Failover-Clustering -IncludeManagementTools 11. Open the command line as an administrator and enter cluadmin.msc top open the Cluster Manager. 12. Open the context menu (right-click) for Failover Cluster Manager, and then choose Create Cluster. 13. Choose Next > Browse. Deployment options 41 Microsoft SQL Server on Amazon EC2 User Guide 14. For Enter the object names to select, enter the cluster node hostnames, and then choose OK. 15. Choose Next. You can now choose whether to validate the cluster. We recommend that you perform a cluster validation. If the cluster does not pass validation Microsoft may be unable to provide technical support for your SQL cluster. Choose Yes or No, and then choose Next. 16. Enter a Cluster Name, and then choose Next. 17. Clear Add all eligible storage to the cluster, and then choose Next. 18. When the cluster creation is complete, choose Finish. Note Cluster logs and reports are located at %systemroot%\cluster\reports. 19. In the Cluster Core Resources section of Cluster Manager, expand the entry for your new cluster. 20. Open the context menu (right-click) for the first IP address entry, and then choose Properties. For IP Address , choose Static IP Address, and then enter one of the secondary IP addresses associated with the eth0 elastic network interface. Choose OK. Repeat this step for the second IP address entry. 21. Open the context menu (right-click) for the cluster name, and then choose Bring Online. Note We recommend that you configure a File Share Witness (FSW) in addition to your cluster to act as a tie-breaker. You can also use Amazon FSx for Windows File Server with Microsoft SQL Server. Create Always On availability groups Perform the following steps to create Always On availability groups. 1. Open SQL Server Configuration Manager. 2. Open the context menu (right-click) for the SQL instance, and then choose Properties. 3. On the AlwaysOn High Availability tab, select Enable AlwaysOn Availability Groups, and then choose Apply. 4. Open the context menu (right-click) for the SQL instance, and then choose Restart. Deployment options 42 Microsoft SQL Server on Amazon EC2 User Guide 5. Repeat steps 1 through 4 on the other cluster node to include in the cluster. 6. Open Microsoft SQL Server Management Studio (SSMS). 7. Log in to one of the SQL instances with your Windows authenticated login that has access to the SQL instance. Note We recommend that you use the same MDF and LDF directory file paths across the SQL instances. 8. Create a test database. Open the context menu (right-click) for Databases, and then choose New Database. Note Make sure that you use the Full recovery model on the Options page. 9. Enter a Database name, and then choose OK. 10. Open the context menu (right-click) for the new database name, choose Tasks, and then choose Back Up For Backup type, choose Full. 11. Choose OK > OK. 12. Open the context menu (right-click) for Always On High Availability and then choose New Availability Group Wizard. 13. Choose Next. 14. Enter an Availability group name, and then choose Next. 15. Select your database, and then choose Next. 16. A primary replica is already present in the Availability Replicas window. Choose Add Replica to create a secondary replica. 17. Enter a Server name for the secondary replica and then choose Connect. 18. Decide which Availability Mode you want to use for each replica, and then choose either Synchronous commit or Asynchronous commit. 19. Choose Next. 20. Choose your data synchronization preference, and then choose Next. 21. When the validation is successful, choose Next. Deployment options 43 Microsoft SQL Server on Amazon EC2 User Guide Note You can safely ignore Checking the listener configuration because you will add it later. 22. Choose Finish > Close. Add a SQL Group Listener Perform the following steps to add a SQL Group Listener. 1. Open SQL Server Management Studio (SSMS) and expand Always On High Availability, Availability Groups, <primary replica name>. 2. Open the context menu (right-click) for Availability Group Listeners and then choose Add Listener. Enter a DNS Name. 3. Enter Port 1433. 4. Choose Static IP for Network Mode. 5. Choose Add. For the IPv4 Address, enter the second secondary IP address from one of the cluster node instances, and then choose OK. Repeat this step
sql-server-ec2-020
sql-server-ec2.pdf
20
you will add it later. 22. Choose Finish > Close. Add a SQL Group Listener Perform the following steps to add a SQL Group Listener. 1. Open SQL Server Management Studio (SSMS) and expand Always On High Availability, Availability Groups, <primary replica name>. 2. Open the context menu (right-click) for Availability Group Listeners and then choose Add Listener. Enter a DNS Name. 3. Enter Port 1433. 4. Choose Static IP for Network Mode. 5. Choose Add. For the IPv4 Address, enter the second secondary IP address from one of the cluster node instances, and then choose OK. Repeat this step using the second secondary IP address from the other cluster node instance. 6. Choose OK. Note If you receive errors when you add a SQL Group Listener, you may be missing permissions. For troubleshooting see: • Troubleshooting AlwaysOn availability group listener creation in SQL Server 2012 • Create Availability Group Listener Fails with Message 19471, ‘The WSFC cluster could not bring the Network Name resource online’ Deployment options 44 Microsoft SQL Server on Amazon EC2 Test failover User Guide 1. From SSMS, open the context menu (right-click) for the primary replica on the navigation menu, and then choose Failover. 2. Choose Next > Next. 3. Choose Connect > Connect. 4. Choose Next, and then choose Finish. The primary replica will become the secondary replica after failover. Deployment options 45 Microsoft SQL Server on Amazon EC2 User Guide Connect to Microsoft SQL Server on Amazon EC2 You can connect to your Microsoft SQL Server instance using one of the following tools. Topics • SQL Server Management Studio (SSMS) • SQL Server Configuration Manager SQL Server Management Studio (SSMS) By default, only the built-in local administrator account can access a SQL Server instance launched from an AWS Windows AMI. You can use SQL Server Management Studio (SSMS) to add domain users so that they can access and manage SQL Server. Perform the following steps to access a SQL Server instance on Amazon EC2 as a domain user. 1. Connect to your instance as a local administrator using Remote Desktop Protocol (RDP). 2. Open SQL Server Management Studio (SSMS). 3. For Authentication, choose Windows Authentication to log in with the built-in local administrator. 4. (Optional) Allow domain users to log in. a. b. Choose Connect. In Object Explorer, expand Security. c. Open the context menu (right-click) for Logins then select New Login. d. For Login name, select Windows authentication. Enter Domain\username, replacing DomainName with your domain NetBIOS name and username with your Active Directory user name. e. On the Server roles page, select the server roles that you want to grant to the Active Directory user. Select the General page, and then choose OK. Log out from the instance and then log in again as a domain user. f. g. h. Open SSMS. For Authentication, choose Windows authentication to log in with your domain user account. SSMS 46 Microsoft SQL Server on Amazon EC2 i. Choose Connect. User Guide SQL Server Configuration Manager To connect to SQL Server using SQL Server Configuration Manager, see SQL Server Configuration Manager in the Microsoft documentation. Configuration Manager 47 Microsoft SQL Server on Amazon EC2 User Guide Microsoft SQL Server on Amazon EC2 backup with the AWS VSS solution You can use the AWS VSS solution to create snapshots of the volumes attached to your EC2 instance, including data from your Microsoft SQL Server database. The AWS VSS solution uses Amazon managed command documents with the AWS Systems Manager Run Command. The snapshot process uses the Windows Volume Shadow Copy Service (VSS) to create EBS volume-level backups without requiring you to shut down or pause your SQL Server application or disconnect active connections. There is no additional cost to use the AWS VSS solution to create EBS snapshots. You only pay for EBS snapshots created by the backup process. For more information, see How am I billed for my Amazon EBS snapshots? To restore your SQL Server databases from AWS VSS solution based EBS snapshots, see Use an automation runbook to restore your database from AWS VSS solution snapshots. AWS VSS solution based snapshot prerequisites To start backing up your SQL Server databases with AWS VSS solution based EBS snapshots, you must meet all of the prerequisites. • Your instance must satisfy the system requirements, and have the appropriate IAM permissions attached to your instance profile role. If you use Systems Manager to run the recommended command document (AWSEC2-VssInstallAndSnapshot), you can skip the component install prerequisite. That command document automatically installs the VSS components as needed on your instance. For more information, see Prerequisites to create Windows VSS based EBS snapshots in the Amazon EC2 User Guide. • To enable the restore process for your SQL Server database, you must set your database to full recovery mode
sql-server-ec2-021
sql-server-ec2.pdf
21
based EBS snapshots, you must meet all of the prerequisites. • Your instance must satisfy the system requirements, and have the appropriate IAM permissions attached to your instance profile role. If you use Systems Manager to run the recommended command document (AWSEC2-VssInstallAndSnapshot), you can skip the component install prerequisite. That command document automatically installs the VSS components as needed on your instance. For more information, see Prerequisites to create Windows VSS based EBS snapshots in the Amazon EC2 User Guide. • To enable the restore process for your SQL Server database, you must set your database to full recovery mode before you take the snapshot. To configure recovery mode, see View or change the recovery model of a database (SQL Server) on the Microsoft Learn website. Snapshot prerequisites 48 Microsoft SQL Server on Amazon EC2 User Guide Create AWS VSS solution based EBS snapshots To create EBS snapshots that you can use to restore your database instance, see Use Systems Manager command documents to create VSS based snapshots. We recommend that you run the AWSEC2-VssInstallAndSnapshot command document, which automatically installs the VSS components as needed on your instance. Note To ensure that you can use the AWS VSS solution snapshots to restore your database, set the SaveVssMetadata parameter to True for your command document before you run it. Create AWS VSS solution based EBS snapshots 49 Microsoft SQL Server on Amazon EC2 User Guide Use an automation runbook to restore your database from AWS VSS solution snapshots This guide explains how to use the AWSEC2-RestoreSqlServerDatabaseWithVss automation runbook to restore a Microsoft SQL Server database running on an EC2 instance from application- consistent snapshots created by the AWS VSS solution. You can tailor the restoration parameters to your specific needs, such as setting the database to restore mode after restoration. By leveraging Windows VSS technology, this solution offers the following advantages: • Fast restoration times. • The ability to perform the restore without shutting down or pausing the Microsoft SQL Server application. For more information about the AWS VSS solution, see Application consistent Windows VSS based Amazon EBS snapshots in the Amazon EC2 User Guide. Contents • Pricing • VSS snapshot restore prerequisites • Restore your SQL Server database from VSS snapshots • Troubleshoot restoring your SQL Server database from AWS VSS solution snapshots Pricing The AWS VSS solution uses AWS Systems Manager automation runbooks with EBS resources to restore a Microsoft SQL Server database on an EC2 instance. Associated costs include the following: Systems Manager Automation With Systems Manager automation runbooks, you pay only for what you use and are charged based on the number and duration of steps, which includes a free tier per account. If you created an organization, your free tier usage is shared across all accounts in the Consolidated Billing family. For more information about Systems Manager automation pricing, see Automation. Pricing 50 Microsoft SQL Server on Amazon EC2 Amazon EBS User Guide During restore steps, the AWS VSS solution creates a new EBS volume and restores data from VSS based EBS snapshots. With Amazon EBS resources, you pay only for what you provision. For more information, see Amazon EBS pricing. VSS snapshot restore prerequisites To restore your SQL Server databases from AWS VSS solution based EBS snapshots, you must meet the following prerequisites. Note The AWSEC2-RestoreSqlServerDatabaseWithVss automation runbook only supports restoring snapshots to the original EC2 instance where the snapshots were created. • Disk management configuration – Your EC2 database instance must be configured with Basic Disks. For more information, see Basic Disks on the Microsoft Learn website. • Microsoft SQL Server deployment options – To restore a SQL Server database with the AWSEC2-RestoreSqlServerDatabaseWithVss automation runbook, the database must either be configured as a standalone deployment, or be the primary database in a Microsoft SQL Server Always On availability group. For more information, see Deployment options. • Configure settings to save VSS metadata files – To successfully initiate a restore operation, the following two VSS metadata files are required. These files are generated for each snapshot set taken during the snapshotting process. • {Snapshot set id}-{timestamp}-BackupComponentDocument.xml • {Snapshot set id}-{timestamp}-SqlServerWriter.xml To ensure that these files are generated, set the SaveVssMetadata parameter to true when you run the command document. • Grant IAM permissions for the restore process. Prerequisites 51 Microsoft SQL Server on Amazon EC2 User Guide Grant IAM permissions for the restore process The AWSEC2-RestoreSqlServerDatabaseWithVss automation runbook needs permission to perform the Amazon EC2 and Systems Manager operations that the runbook uses to restore the database. Follow these steps to grant the appropriate permissions. 1. Create an IAM policy to restore a SQL Server database from AWS VSS solution based snapshots. 2. Attach the IAM policy to the role that's used for the automation runbook. Create an IAM policy to restore a SQL Server
sql-server-ec2-022
sql-server-ec2.pdf
22
run the command document. • Grant IAM permissions for the restore process. Prerequisites 51 Microsoft SQL Server on Amazon EC2 User Guide Grant IAM permissions for the restore process The AWSEC2-RestoreSqlServerDatabaseWithVss automation runbook needs permission to perform the Amazon EC2 and Systems Manager operations that the runbook uses to restore the database. Follow these steps to grant the appropriate permissions. 1. Create an IAM policy to restore a SQL Server database from AWS VSS solution based snapshots. 2. Attach the IAM policy to the role that's used for the automation runbook. Create an IAM policy to restore a SQL Server database from AWS VSS solution based snapshots To create the IAM policy that grants the permissions needed to restore a Microsoft SQL Server database from VSS based snapshots in the AWS Management Console, follow these steps. 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. In the navigation pane, choose Policies, and then choose Create policy. 3. Choose JSON in the policy editor panel. 4. Copy the following policy content into the editor. This policy grants permissions to create volumes from VSS snapshots, attach them to instances, and invoke the SSM SendDocument and GetDocument API operations to run the automation document for database restoration. Note (Optional) To enhance security, you can further customize the policy by implementing custom conditions or specifying exact resource ARNs. { "Version": "2012-10-17", "Statement": [ { "Sid": "CreateVolumeAccessVolume", "Effect": "Allow", "Action": "ec2:CreateVolume", "Resource": "*", "Condition": { Grant IAM permissions for the restore process 52 Microsoft SQL Server on Amazon EC2 User Guide "StringLike": { "aws:RequestTag/AwsVssConfig": "*" }, "ArnLike": { "ec2:ParentSnapshot": "*" } } }, { "Sid": "CreateVolumeWithTagging", "Effect": "Allow", "Action": "ec2:CreateTags", "Resource": "arn:aws:ec2:*:*:volume/*", "Condition": { "StringEquals": { "ec2:CreateAction": "CreateVolume" } } }, { "Sid": "AttachVolumeAccessVolume", "Effect": "Allow", "Action": "ec2:AttachVolume", "Resource": "*", "Condition": { "StringLike": { "ec2:ResourceTag/AwsVssConfig": "*" } } }, { "Sid": "AttachVolumeAccessInstance", "Effect": "Allow", "Action": "ec2:AttachVolume", "Resource": "arn:aws:ec2:*:*:instance/*" }, { "Sid": "DescribeVolumes", "Effect": "Allow", "Action": "ec2:DescribeVolumes", "Resource": "*" }, { "Sid": "DescribeSnapshots", Grant IAM permissions for the restore process 53 Microsoft SQL Server on Amazon EC2 User Guide "Effect": "Allow", "Action": "ec2:DescribeSnapshots", "Resource": "*" }, { "Sid": "DescribeInstanceAttribute", "Effect": "Allow", "Action": "ec2:DescribeInstanceAttribute", "Resource": "arn:aws:ec2:*:*:instance/*" }, { "Sid": "SsmAutomationRead", "Effect": "Allow", "Action": [ "ssm:DescribeInstanceInformation", "ssm:ListCommandInvocations", "ssm:ListCommands" ], "Resource": "*" }, { "Sid": "SsmRunCommand", "Effect": "Allow", "Action": [ "ssm:SendCommand", "ssm:GetDocument" ], "Resource": [ "arn:aws:ec2:*:*:instance/*", "arn:aws:ssm:*:*:automation-definition/AWSEC2- RestoreSqlServerDatabaseWithVss", "arn:aws:ssm:*:*:document/AWS-ConfigureAWSPackage", "arn:aws:ssm:*:*:document/AWSEC2-PrepareVssRestore", "arn:aws:ssm:*:*:document/AWSEC2-RunVssRestoreForSqlDatabase" ] } ] } 5. Choose Next. 6. Enter a unique name and optional description for your policy, then choose Create policy. Grant IAM permissions for the restore process 54 Microsoft SQL Server on Amazon EC2 User Guide Attach the IAM policy to the role that's used for the automation runbook You can choose from the following options to attach your policy to the role that Systems Manager uses for the AWSEC2-RestoreSqlServerDatabaseWithVss automation runbook. • Create a role, attach your policy, and add a PassRole policy to restrict access. The automation assumes the role that's specified in the AutomationAssumeRole parameter. Expand the Invoke automation with an assumed role (recommended) section to see detailed steps. • Attach the policy to your console role. The automation uses the console role that's defined for your current session. Expand the Invoke automation with current session’s console role section to see detailed steps. Invoke runbook automation with an assumed role (recommended) Step 1: Create the role that the automation assumes and attach your policy 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. 3. 4. 5. In the navigation pane, choose Roles, and then choose Create role. This opens the Select trusted entity page. In the Trusted entity type panel, choose AWS service. This is the default selection. In the Use case panel, select Systems Manager from the list, and then choose Next. This opens the Add permissions page. Search for the name of the policy that you created for the database restore runbook. Select the check box next to the name and then choose Next. This takes you to the Name, review, and create page. 6. In the Role details panel, enter Role name and Description. 7. When you've finished reviewing, choose Create role. This takes you back to the Roles page. 8. Open the detail page for the role that you just created. Take note of the Role Name at the top for future reference. Copy the Role ARN from the Summary panel to use in the next steps, then continue to Step 2 to create a PassRole policy for your role. Grant IAM permissions for the restore process 55 Microsoft SQL Server on Amazon EC2 User Guide Step 2: Create an inline policy to pass the role that the automation assumes 1. In the detail page for the role that you just created, choose the Permissions tab. 2. Choose Add inline policy from the Add permissions menu. This opens the Specify permissions
sql-server-ec2-023
sql-server-ec2.pdf
23
Take note of the Role Name at the top for future reference. Copy the Role ARN from the Summary panel to use in the next steps, then continue to Step 2 to create a PassRole policy for your role. Grant IAM permissions for the restore process 55 Microsoft SQL Server on Amazon EC2 User Guide Step 2: Create an inline policy to pass the role that the automation assumes 1. In the detail page for the role that you just created, choose the Permissions tab. 2. Choose Add inline policy from the Add permissions menu. This opens the Specify permissions page. 3. Select the Visual policy editor. 4. Choose IAM from the Service list. 5. 6. 7. In the Actions allowed search box, enter PassRole, then select the PassRole check box. The Resources panel opens with the Specific option selected by default. Select the Add ARNs link to open a panel where you can specify the ARN for your role. In the Resource ARN box, paste the ARN that you copied at the end of Step 1. IAM automatically populates the role name based on the ARN. 8. Choose Add ARNs to save your resource ARN. This takes you back to the Specify permissions page, and shows your entry. 9. Choose Next to review your policy. This opens the Review and create page. 10. On the Review Policy page, enter a name (for example, VssRestorePassRolePolicy) and then choose Next to create the PassRole policy for your role. Invoke automation with the console role for your current session 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. In the navigation pane, choose Roles, and then select the role that your current console session is using. The current role appears in the upper right corner of the console, where you'll see the following pattern: role/user @ account 3. In the Permissions tab, choose Attach policies from the Add permissions menu. This opens the Attach policy to <selected role> page. 4. Use the search bar in the Other permissions policies panel to search for the name of the policy that you created for the database restore runbook. Select the check box next to the name and then choose Add permissions. Grant IAM permissions for the restore process 56 Microsoft SQL Server on Amazon EC2 User Guide Restore your SQL Server database from VSS snapshots The AWSEC2-RestoreSqlServerDatabaseWithVss automation runbook provides a streamlined process to restore your SQL Server databases. This guide outlines the automation runbook functionality and explains the parameters that you can customize to suit your specific restoration needs. Before you run the AWSEC2-RestoreSqlServerDatabaseWithVss automation runbook, ensure that you've met all prerequisites to create application consistent snapshots with the AWS VSS solution. For more information, see Prerequisites to create Windows VSS based EBS snapshots in the Amazon EC2 User Guide. The AWSEC2-RestoreSqlServerDatabaseWithVss process consists of several key steps, as follows. 1. The first step uses AWS-ConfigureAwsPackage to upgrade or install the latest version of the AwsVssComponents component package. 2. The next step invokes AWSEC2-PrepareVssRestore to verify that prerequisites are met and that the input parameters include a valid value for the VSS Snapshot Set ID. 3. The process then creates new EBS volumes from the snapshots and attaches them to the instance. 4. Finally, the process invokes AWSEC2-RunVssRestoreForSqlDatabase, which runs the Amazon EC2 VSS Agent to restore the database on the instance, and returns volume IDs and their usage status by the restored database, the final restore operation status, and Amazon EC2 VSS Agent logs. Parameters for the SQL Server database restore runbook The AWSEC2-RestoreSqlServerDatabaseWithVss automation runbook uses the following input parameters: Note You can provide one of the following parameters to use a specific snapshot: • SnapshotSetId • RestorePointOfTime Restore from VSS snapshots 57 Microsoft SQL Server on Amazon EC2 User Guide If both parameters are empty, the restore uses the most recent snapshot set. InstanceId (string, required) The ID of the Amazon EC2 instance where the restore is performed. SourceDatabaseName (string, required) The name of the database that's included in the snapshots. TargetDatabaseName (string, optional) The restore process creates a new database, and restores the data from the snapshots to the new database from the snapshots. You can optionally set the name, or leave this parameter empty to use the default name for the new database (Db_Restored). The old database files are removed from the volume after the process completes. SnapshotSetId (string, optional) The Snapshot Set ID of the snapshot to use for recovery. RestorePointOfTime (string, optional) If this parameter is specified, the restore process uses the last Snapshot Set that was created before the provided point in time value. This parameter uses the following string format: MM- dd-yyyy:hh-mm. RestoreWithNorecovery (string, required) If this parameter is set to True the restore process leaves the database in restoring state so that you can
sql-server-ec2-024
sql-server-ec2.pdf
24
or leave this parameter empty to use the default name for the new database (Db_Restored). The old database files are removed from the volume after the process completes. SnapshotSetId (string, optional) The Snapshot Set ID of the snapshot to use for recovery. RestorePointOfTime (string, optional) If this parameter is specified, the restore process uses the last Snapshot Set that was created before the provided point in time value. This parameter uses the following string format: MM- dd-yyyy:hh-mm. RestoreWithNorecovery (string, required) If this parameter is set to True the restore process leaves the database in restoring state so that you can apply transaction logs after the database restore is completed. To bring the database online immediately after the restore is completed, set this parameter to False. MetadataPath (string, optional) The fully qualified path to the directory where the VSS metadata files are stored. If not specified, the system uses the following default location, where metadata files are automatically saved during snapshot operations. Use this parameter to indicate a custom storage location if you've relocated the files. %PROGRAMDATA%\Amazon\AwsVss \VssMetadata. Runbook parameters 58 Microsoft SQL Server on Amazon EC2 User Guide AutomationAssumeRole (string, conditional) The ARN of the IAM role for the automation to assume. • Console: If this parameter is not specified, the restore process uses the IAM role for the current console session. • Command line: If this parameter is not specified, the restore process uses the IAM role for your current session. ExecutionTimeout (string, optional) The amount of time, in seconds, that the RunVssRestoreForSqlDatabase step can run before it fails. If this value is not specified, the default timeout is 600 seconds. Run the SQL Server database restore process 1. Always On databases: Remove the source database from the SQL Server availability group If your database is the primary database in an Always On availability group, you must remove the database from the availability group before you run the restore process. a. To remove the database from the availability group, follow the steps described in Remove a primary database from an Always On availability group on the Microsoft Learn website. b. Verify that the database remains online, and is not in a Synchronized state. 2. Execute AWSEC2-RestoreSqlServerDatabaseWithVss Automation Runbook To view instructions, select the tab that matches your environment. AWS Management Console To run the restore in the AWS Management Console, follow these steps: 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. Select Automation from the navigation pane, under Change Management Tools. This shows a list of automation executions in your account, if applicable. 3. Choose Execute automation. This opens the Choose runbook page. Run the restore process 59 Microsoft SQL Server on Amazon EC2 User Guide 4. In the Owned by Amazon tab, search for AWSEC2- RestoreSqlServerDatabaseWithVss, and select it from the results. This opens the Runbook details panel. 5. Select Default version at runtime from the Runbook version list. 6. Choose Next. This opens the page where you can configure the settings and enter input parameters for the runbook. 7. Enter values for the Input parameters to configure runtime settings for the restore process. For parameter details, see Parameters for the SQL Server database restore runbook. 8. Choose Execute to run the automation. To review the execution status, navigate to the Executed Steps section within the automation execution details. This section displays all of the steps that ran, along with their runtime status. If the automation execution failed, follow the troubleshooting steps outlined in Before you try any troubleshooting steps, we recommend that you verify that you've met all VSS snapshot restore prerequisites. Debug failures in AWSEC2-RestoreSqlServerDatabaseWithVss from the Systems Manager console In the Systems Manager console, the Failure details section in the automation runbook Execution Details page includes the following information: • Failure Message • Failure Type • Failure Stage Together, these details offer a general overview of the cause of the failure. For a more comprehensive understanding, you must examine the specific step execution that failed. The steps in AWSEC2-RestoreSqlServerDatabaseWithVss can be classified into three main categories: Debug failures in AWSEC2-RestoreSqlServerDatabaseWithVss from the Systems Manager console 60 Microsoft SQL Server on Amazon EC2 User Guide Script Execution Steps These use the aws:executeScript action and include the following steps. • PrepareForVolumeCreation • ExtractCurrIterValues • ConcatVolumeIds If one of these steps fails, investigate the step execution and review the execution logs found under OutputPayload in the Outputs section to determine what caused the issue. EC2 API Interaction Steps These interact with Amazon EC2 APIs to create volumes from snapshots, attach them to instances, and monitor volume status. Many of these steps are performed within loop steps. If a loop step fails, identify the specific step within the loop that caused the failure to pinpoint the root cause. The Failure details section in the step execution
sql-server-ec2-025
sql-server-ec2.pdf
25
and include the following steps. • PrepareForVolumeCreation • ExtractCurrIterValues • ConcatVolumeIds If one of these steps fails, investigate the step execution and review the execution logs found under OutputPayload in the Outputs section to determine what caused the issue. EC2 API Interaction Steps These interact with Amazon EC2 APIs to create volumes from snapshots, attach them to instances, and monitor volume status. Many of these steps are performed within loop steps. If a loop step fails, identify the specific step within the loop that caused the failure to pinpoint the root cause. The Failure details section in the step execution details page provides relevant information for debugging. Run Command Execution Steps These use the aws:RunCommand action to execute commands on the target instance. If a failure occurs due to a run command execution, examine the step execution details. Under Outputs, select the CommandId link for the command to access the Run command execution page, where you can view the complete log for debugging purposes. . • Locate the command execution ID in the step details. • Select the linked ID to access the execution details. • Inspect the command output and return code for further troubleshooting. Debug failures in AWSEC2-RestoreSqlServerDatabaseWithVss from the Systems Manager console 61 Microsoft SQL Server on Amazon EC2 AWS CLI User Guide Run the following command to restore a Microsoft SQL Server database on an instance. Replace or add parameters based on your specific use case. For parameter details, see Parameters for the SQL Server database restore runbook. aws ssm start-automation-execution \ --document-name "AWSEC2-RestoreSqlServerDatabaseWithVss" \ --parameters '{"InstanceId":"i-1234567890abcdef0","SourceDatabaseName":"DB_Source","TargetDatabaseName":"DB_Restored"}' Get execution status To get the status of the automation execution, run the following command using the execution ID returned from start-automation-execution. aws ssm get-automation-execution \ --automation-execution-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 PowerShell Run the following PowerShell commands with AWS Tools for Windows PowerShell to restore a SQL Server database on an instance. Replace or add parameters based on your specific use case. For parameter details, see Parameters for the SQL Server database restore runbook. Start-SSMAutomationExecution ` -DocumentName "AWSEC2-RestoreSqlServerDatabaseWithVss" ` -Parameter @{"InstanceId" = @($InstanceId); "SourceDatabaseName" = @("DB_Source"); "TargetDatabaseName" = @("DB_Restored"); "RestoreWithNorecovery" = @($True); "AutomationAssumeRole" = @("Arn:of:role")} Get execution status To get the status of the automation execution and the status of each action step, run the following command using the execution ID returned from Start- SSMAutomationExecution. Debug failures in AWSEC2-RestoreSqlServerDatabaseWithVss from the Systems Manager console 62 Microsoft SQL Server on Amazon EC2 User Guide Get-SSMAutomationExecution -AutomationExecutionId $ExecutionId | Select-Object - ExpandProperty StepExecutions | Select-Object -Property StepName, StepStatus | Out-String 3. Clean up unused EBS volumes after the automation execution succeeds The AWSEC2-RestoreSqlServerDatabaseWithVss automation creates a new EBS volume for each volume snapshot within a VSS snapshot set. These volumes are then attached to the target instance. The database files may not be located on all volumes, so you can detach and delete the unused ones. a. In the Execution detail page, choose the RunVssRestoreForSqlDatabase step (this is the last step). b. Choose the CommandId link in the Outputs section, and then choose the instance id to view the run command output. c. At the end of the output is a list of all volumes created and attached to the instance for restore purposes, and the status for each one. The status is either in-use or unused. To detach and delete the volumes, see Detach an Amazon EBS volume from an Amazon EC2 instance in the Amazon EBS User Guide. Troubleshoot restoring your SQL Server database from AWS VSS solution snapshots Before you try any troubleshooting steps, we recommend that you verify that you've met all VSS snapshot restore prerequisites. Debug failures in AWSEC2-RestoreSqlServerDatabaseWithVss from the Systems Manager console In the Systems Manager console, the Failure details section in the automation runbook Execution Details page includes the following information: • Failure Message • Failure Type • Failure Stage Troubleshoot VSS snapshot restore 63 Microsoft SQL Server on Amazon EC2 User Guide Together, these details offer a general overview of the cause of the failure. For a more comprehensive understanding, you must examine the specific step execution that failed. The steps in AWSEC2-RestoreSqlServerDatabaseWithVss can be classified into three main categories: Script Execution Steps These use the aws:executeScript action and include the following steps. • PrepareForVolumeCreation • ExtractCurrIterValues • ConcatVolumeIds If one of these steps fails, investigate the step execution and review the execution logs found under OutputPayload in the Outputs section to determine what caused the issue. EC2 API Interaction Steps These interact with Amazon EC2 APIs to create volumes from snapshots, attach them to instances, and monitor volume status. Many of these steps are performed within loop steps. If a loop step fails, identify the specific step within the loop that caused the failure to pinpoint the root cause. The Failure details section in the step execution details page provides relevant information for debugging.
sql-server-ec2-026
sql-server-ec2.pdf
26
• ExtractCurrIterValues • ConcatVolumeIds If one of these steps fails, investigate the step execution and review the execution logs found under OutputPayload in the Outputs section to determine what caused the issue. EC2 API Interaction Steps These interact with Amazon EC2 APIs to create volumes from snapshots, attach them to instances, and monitor volume status. Many of these steps are performed within loop steps. If a loop step fails, identify the specific step within the loop that caused the failure to pinpoint the root cause. The Failure details section in the step execution details page provides relevant information for debugging. Run Command Execution Steps These use the aws:RunCommand action to execute commands on the target instance. If a failure occurs due to a run command execution, examine the step execution details. Under Outputs, select the CommandId link for the command to access the Run command execution page, where you can view the complete log for debugging purposes. Debug failures in AWSEC2-RestoreSqlServerDatabaseWithVss from the Systems Manager console 64 Microsoft SQL Server on Amazon EC2 User Guide Evaluate if you can downgrade your Microsoft SQL Server edition If you find that you aren't using Enterprise edition features, you can consider downgrading to Microsoft SQL Server Standard or Developer edition. By downgrading the edition, you can save on licensing costs. Note SQL Server Developer edition is only eligible for use in non-production, development, and test workloads. Downgrade requirements Your Microsoft SQL Server on Amazon EC2 must use the Bring Your Own License model (BYOL) and SQL Server Enterprise edition to be eligible for an in-place downgrade. If your instance meets this criteria, you should carefully evaluate which features are being used on your SQL Server instance before performing any changes. You can review the following SQL Server Enterprise edition features and instance level constraints to help evaluate your downgrade eligibility. Tip A script is available to help evaluate if you can downgrade your SQL Server edition. For more information, see Downgrade SQL Server Enterprise edition using AWS Systems Manager Document to reduce cost. Confirm that your instance has less than the following resources available: • 48 vCPUs • 128 GiB of memory If your instance is under-utilized for your workload, you can change the instance type or size your instance to meet these requirements. For more information, see Change the instance type . Downgrade requirements 65 Microsoft SQL Server on Amazon EC2 User Guide Confirm that you aren't using any of the following SQL Server Enterprise edition features: • Database-level enterprise features • Always On availability groups • Online index operations • Resource Governor • Peer-to-peer or Oracle replication • R or Python extensions • Memory-optimized tempdb metadata The following diagram walks through an evaluation for some of the downgrade requirements: If your workload doesn't utilize any of the previously listed features, you should continue to evaluate if you use any less common SQL Server Enterprise edition features. For more information about SQL Server Enterprise editions and supported features, see the Microsoft documentation for your SQL Server version: • SQL Server 2022 • SQL Server 2019 • SQL Server 2017 Downgrade requirements 66 Microsoft SQL Server on Amazon EC2 • SQL Server 2016 • SQL Server 2014 User Guide Downgrade your SQL Server Enterprise edition If you determine that you can downgrade your SQL Server Enterprise edition, you can follow this process to convert to SQL Server Standard or Developer edition. For information on how to automate for this process, see Downgrade SQL Server Enterprise edition using AWS Systems Manager Document to reduce cost. Important • This process will require downtime for your SQL Server instance. Your database will not be operational until the entire procedure has been completed successfully. • Only SQL Server instances using BYOL software support in-place downgrading. For more information, see Licensing options. To downgrade your SQL Server Enterprise edition 1. Create a Full backup of all user and system databases. Ensure that the backup completes successfully before continuing. 2. Note your current SQL Server minor version, service pack, cumulative updates, and the General Distribution Release (GDR). For more information, see Determine which version and edition of SQL Server Database Engine is running in the Microsoft documentation. 3. Detach all user databases. 4. Stop the SQL Server Database Engine service and copy the log and system database data files —master, model, and msdb—to a local backup folder. 5. Uninstall SQL Server Enterprise edition including all components. 6. Reboot the instance. 7. 8. 9. Install SQL Server Standard or Developer edition according to your requirement. Install the same service packs and cumulative updates that you had before the uninstall. Stop the SQL Server Database Engine service. 10. Using the backups you made in step 4, restore the master, model, and msdb databases. Downgrade your SQL Server Enterprise edition 67 Microsoft
sql-server-ec2-027
sql-server-ec2.pdf
27
all user databases. 4. Stop the SQL Server Database Engine service and copy the log and system database data files —master, model, and msdb—to a local backup folder. 5. Uninstall SQL Server Enterprise edition including all components. 6. Reboot the instance. 7. 8. 9. Install SQL Server Standard or Developer edition according to your requirement. Install the same service packs and cumulative updates that you had before the uninstall. Stop the SQL Server Database Engine service. 10. Using the backups you made in step 4, restore the master, model, and msdb databases. Downgrade your SQL Server Enterprise edition 67 Microsoft SQL Server on Amazon EC2 11. Start SQL Server service. User Guide 12. Attach the mdf and ldf user databases that were detached in step 3 to your SQL Server instance. 13. Confirm that your database is operating as expected. Downgrade your SQL Server Enterprise edition 68 Microsoft SQL Server on Amazon EC2 User Guide Migrating an on-premises database to Amazon EC2 You can migrate your on-premises Microsoft SQL Server database to Amazon Elastic Compute Cloud (Amazon EC2). If you select a migration method and perform these steps, your on-premises database will reside on an Amazon EC2 instance running Windows Server. On-premises migration methods • Automated SQL Server backup and restore • Manual SQL Server backup and restore • Server rehost Automated SQL Server backup and restore You can use AWS Migration Hub Orchestrator to orchestrate and automate the migration of SQL Server databases to Amazon EC2 using automated native backup and restore. This feature of AWS Migration Hub uses predefined workflow templates that are built based on best practices. Migration Hub Orchestrator automates error-prone manual tasks involved in the migration process, such as checking environment readiness and connections. For more information, see Rehost SQL Server on Amazon EC2 in the Migration Hub Orchestrator User Guide. Manual SQL Server backup and restore You can use native backup files as a way to restore SQL Server databases without additional dependencies. You can back up and restore individual databases, or the entire database instance, from on premises to your EC2 instance. Manual migration topics • Prerequisites • Step 1: Backing up your database • Step 2: Uploading your database backup files • Step 3: Downloading your database backup files • Step 4: Restoring your database backup files Automated SQL Server backup and restore 69 Microsoft SQL Server on Amazon EC2 Prerequisites User Guide You must meet the following prerequisites to migrate an on-premises database to Amazon EC2 using Amazon Simple Storage Service (Amazon S3): • An active AWS account. For more information, see Set up Microsoft SQL Server on Amazon EC2. • A source SQL Server database running on premises that you'd like to migrate. • A destination EC2 instance running Windows Server with SQL Server installed on it. It is preferred that the destination instance’s SQL Server version is the same or higher than the source SQL Server version running on premises. For more information on how to launch an instance, see Launch your instance in the Amazon EC2 User Guide. • An Amazon Simple Storage Service (Amazon S3) bucket. For more information, see Creating, configuring, and working with Amazon S3 buckets in the Amazon S3 User Guide. • Microsoft SQL Server Management Studio (SSMS) has been installed on the destination EC2 instance. For more information, see Download SQL Server Management Studio (SSMS) in the Microsoft documentation. Step 1: Backing up your database You will need to create a full backup of the database as well as back up the Transaction Log for the on-premises SQL Server to capture all of the necessary data for restoration. This procedure generates the backup files can restore your database with in an EC2 instance. To back up an on-premises database 1. Create a full backup of your database. For more information about how to create a full backup of your database, see Create a Full Database Backup in the Microsoft documentation. 2. Create a backup of the Transaction Log. For more information about how to back up the transaction log, see Back up a Transaction Log in the Microsoft documentation. 3. Make a note of the backup file locations, because you will need to upload them to Amazon S3 in the next step. Step 2: Uploading your database backup files With the backup files created, you can now upload them to Amazon S3. Prerequisites 70 Microsoft SQL Server on Amazon EC2 User Guide To upload your database backup files 1. Determine size of your backup files to see which upload methods are supported. 2. Use the file locations you noted previously to upload your backup files. For more information about how you can upload your database backup files to Amazon S3, see Uploading objects. Step 3: Downloading your database backup files Once the backup
sql-server-ec2-028
sql-server-ec2.pdf
28
upload them to Amazon S3 in the next step. Step 2: Uploading your database backup files With the backup files created, you can now upload them to Amazon S3. Prerequisites 70 Microsoft SQL Server on Amazon EC2 User Guide To upload your database backup files 1. Determine size of your backup files to see which upload methods are supported. 2. Use the file locations you noted previously to upload your backup files. For more information about how you can upload your database backup files to Amazon S3, see Uploading objects. Step 3: Downloading your database backup files Once the backup files have been uploaded to Amazon S3, you can restore them in an EC2 instance. To download your backup files from Amazon S3 in the EC2 instance 1. Connect to your SQL Server instance and open SSMS. For more information, see Connect to Microsoft SQL Server on Amazon EC2. 2. Download the backup files in your Amazon EC2 instance running SQL Server. For more information about downloading your files from Amazon S3, see Downloading an object. 3. Make a note of the backup file locations, because you will need them to restore the database in the next step. Step 4: Restoring your database backup files After you download the backup files, you can connect to your instance and restore them using SSMS. To restore your database 1. Connect to your instance and open SSMS. 2. Restore the full database backup using the backup files noted previously. For more information about restoring your database from the backup files, see Restore a Database Backup Using SSMS in the Microsoft documentation. 3. In the EC2 instance, validate that your database has been restored as expected. Server rehost You can choose to rehost (lift and shift) your entire SQL Server to Amazon EC2 instead of individual databases using AWS Application Migration Service or AWS Migration Hub Orchestrator. Step 3: Downloading your database backup files 71 Microsoft SQL Server on Amazon EC2 User Guide Application Migration Service (MGN) Application Migration Service (MGN) automates the migration of your servers and applications to the cloud during a cutover window. For more information on how you can rehost SQL Server using Application Migration Service, see Quick start guide in the Application Migration Service User Guide. Migration Hub Orchestrator Migration Hub Orchestrator orchestrates and further automates the rehost process for servers and applications. For more information on how you can rehost SQL Server using Migration Hub Orchestrator, see Rehost applications on Amazon EC2 in the Migration Hub Orchestrator User Guide. Server rehost 72 Microsoft SQL Server on Amazon EC2 User Guide Windows to Linux replatforming assistant for Microsoft SQL Server Databases The Windows to Linux replatforming assistant for Microsoft SQL Server Databases service is a scripting tool. It helps you move existing Microsoft SQL Server workloads from a Windows to a Linux operating system. You can use the replatforming assistant with any Windows Server virtual machines (VMs) hosted in the cloud, or with on-premises environments running Microsoft SQL Server 2008 and later. The tool checks for common incompatibilities, exports databases from the Windows VM, and imports into an EC2 instance running Microsoft SQL Server 2017 on Ubuntu 16.04. The automated process results in a ready-to-use Linux VM configured with your selected SQL Server databases that can be used for experimenting and testing. Contents • Concepts • Related services • How Windows to Linux replatforming assistant for Microsoft SQL Server works • Components • Replatforming script prerequisites • Run the Windows to Linux replatforming assistant for SQL Server script Concepts The following terminology and concepts are central to your understanding and use of the Windows to Linux replatforming assistant for Microsoft SQL Server Databases. Backup A Microsoft SQL Server backup copies data or log records from a Microsoft SQL Server database or its transaction log to a backup device, such as a disk. For more information, see Backup Overview (Microsoft SQL Server). Restore A logical and meaningful sequence for restoring a set of Microsoft SQL Server backups. For more information, see Restore and recovery overview ( SQL Server). Concepts 73 Microsoft SQL Server on Amazon EC2 Replatform User Guide A Microsoft SQL Server database can be replatformed from an EC2 Windows instance to an EC2 Linux instance running Microsoft SQL Server. It can also be replatformed to the VMware Cloud running Microsoft SQL Server Linux on AWS. Related services AWS Systems Manager (Systems Manager) gives you visibility and control of your infrastructure on AWS. The Windows to Linux replatforming assistant for Microsoft SQL Server Databases uses Systems Manager to move your Microsoft SQL databases to Microsoft SQL Server on EC2 Linux. For more information about Systems Manager, see the AWS Systems Manager User Guide. How Windows to Linux replatforming assistant for Microsoft SQL Server works Windows to Linux replatforming assistant
sql-server-ec2-029
sql-server-ec2.pdf
29
Windows instance to an EC2 Linux instance running Microsoft SQL Server. It can also be replatformed to the VMware Cloud running Microsoft SQL Server Linux on AWS. Related services AWS Systems Manager (Systems Manager) gives you visibility and control of your infrastructure on AWS. The Windows to Linux replatforming assistant for Microsoft SQL Server Databases uses Systems Manager to move your Microsoft SQL databases to Microsoft SQL Server on EC2 Linux. For more information about Systems Manager, see the AWS Systems Manager User Guide. How Windows to Linux replatforming assistant for Microsoft SQL Server works Windows to Linux replatforming assistant for Microsoft SQL Server Databases allows you to migrate your Microsoft SQL Server databases from an on-premises environment or from an EC2 Windows instance to Microsoft SQL Server 2017 on EC2 Linux using backup and restore. For the destination EC2 Linux instance, you provide either the EC2 instance ID or the EC2 instance type with the subnet ID and EC2 Key Pair. When you run the PowerShell script for the Windows to Linux replatforming assistant for Microsoft SQL Server Databases on the source Microsoft SQL Server databases, the Windows instance backs up the databases to an encrypted Amazon Simple Storage Service (S3) storage bucket. It then restores the backups to an existing Microsoft SQL Server on EC2 Linux instance, or it launches a new Microsoft SQL Server on EC2 Linux instance and restores the backups to the newly created instance. This process can be used to replatform your 2-tier databases running enterprise applications. It also enables you to replicate your database to Microsoft SQL Server on Linux to test the application while the source Microsoft SQL Server remains online. After testing, you can schedule application downtime and rerun the PowerShell backup script during your final cutover. The entire replatforming process can also be automated and run unattended. You can run the Systems Manager SSM document AWSEC2-SQLServerDBRestore to import your existing database backup files into Microsoft SQL Server on EC2 Linux without using the PowerShell backup script. Related services 74 Microsoft SQL Server on Amazon EC2 Components User Guide The Windows to Linux replatforming assistant for Microsoft SQL Server Databases script consists of two main components: 1. A PowerShell backup script, which backs up on-premises Microsoft SQL Server databases to an Amazon S3 storage bucket. It then invokes the SSM Automation document AWSEC2- SQLServerDBRestore to restore the backups to a Microsoft SQL Server on EC2 Linux instance. 2. An SSM Automation document named AWSEC2-SQLServerDBRestore, which restores database backups to Microsoft SQL Server on EC2 Linux. This automation restores Microsoft SQL Server database backups stored in Amazon S3 to Microsoft SQL Server 2017 running on an EC2 Linux instance. You can provide your own EC2 instance running Microsoft SQL Server 2017 Linux, or the automation launches and configures a new EC2 instance with Microsoft SQL Server 2017 on Ubuntu 16.04. The automation supports the restoration of full, differential, and transactional log backups, and accepts multiple database backup files. The automation automatically restores the most recent valid backup of each database in the files provided. For more information, see AWSEC2-SQLServerDBRestore. Replatforming script prerequisites This section covers the steps necessary to run the Windows to Linux replatforming script. Contents • Prerequisites to run the replatforming script • Prerequisites for replatforming to an existing EC2 instance Prerequisites to run the replatforming script In order to run the Windows to Linux replatforming assistant for Microsoft SQL Server Databases script, you must do the following: 1. Install the AWS PowerShell module To install the AWS PowerShell module, follow the steps listed in Installing the AWS Tools for PowerShell on Windows. We recommend that you use PowerShell 3.0 or later for the backup script to work properly. Components 75 Microsoft SQL Server on Amazon EC2 User Guide 2. Install the Windows to Linux replatforming assistant PowerShell backup script To run the Windows to Linux replatforming assistant, download the PowerShell backup script: MigrateSQLServerToEC2Linux.ps1. 3. Add an AWS user profile to the AWS SDK store To add and configure the AWS user profile, see the steps listed in Managing Profiles in the AWS Tools for PowerShell User Guide. Set the following IAM policy for your user profile. { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": "iam:PassRole", "Resource": "arn:aws:iam::123456789012:role/DevTeam*" }, { "Sid": "VisualEditor1", "Effect": "Allow", "Action": [ "ec2:RebootInstances", "ssm:SendCommand", "ssm:GetAutomationExecution", "ec2:DescribeInstances", "ssm:ListCommands", "ec2:CreateTags", "s3:CreateBucket", "ec2:RunInstances", "s3:ListBucket", "ssm:GetCommandInvocation", "s3:PutEncryptionConfiguration", "ec2:DescribeImages", "s3:PutObject", "s3:GetObject", "ssm:StartAutomationExecution", "ssm:DescribeInstanceInformation", "s3:DeleteObject", "ssm:ListCommandInvocations", "s3:DeleteBucket", "ec2:DescribeInstanceStatus" ], Prerequisites to run the replatforming script 76 Microsoft SQL Server on Amazon EC2 "Resource": "*" } ] } 4. Create an IAM instance profile role User Guide To create an IAM instance profile role in order to run Systems Manager on EC2 Linux, see the steps listed under Create an IAM instance profile for Systems Manager in the AWS Systems
sql-server-ec2-030
sql-server-ec2.pdf
30
"Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": "iam:PassRole", "Resource": "arn:aws:iam::123456789012:role/DevTeam*" }, { "Sid": "VisualEditor1", "Effect": "Allow", "Action": [ "ec2:RebootInstances", "ssm:SendCommand", "ssm:GetAutomationExecution", "ec2:DescribeInstances", "ssm:ListCommands", "ec2:CreateTags", "s3:CreateBucket", "ec2:RunInstances", "s3:ListBucket", "ssm:GetCommandInvocation", "s3:PutEncryptionConfiguration", "ec2:DescribeImages", "s3:PutObject", "s3:GetObject", "ssm:StartAutomationExecution", "ssm:DescribeInstanceInformation", "s3:DeleteObject", "ssm:ListCommandInvocations", "s3:DeleteBucket", "ec2:DescribeInstanceStatus" ], Prerequisites to run the replatforming script 76 Microsoft SQL Server on Amazon EC2 "Resource": "*" } ] } 4. Create an IAM instance profile role User Guide To create an IAM instance profile role in order to run Systems Manager on EC2 Linux, see the steps listed under Create an IAM instance profile for Systems Manager in the AWS Systems Manager User Guide. Prerequisites for replatforming to an existing EC2 instance To replatform to an existing instance running Microsoft SQL Server 2017 on Linux, you must: 1. Configure the EC2 instance with an AWS Identity and Access Management (IAM) instance profile and attach the AmazonSSMManagedInstanceCore managed policy. For information about creating an IAM instance profile for Systems Manager and attaching it to an instance, see the following topics in the AWS Systems Manager User Guide: • Create an IAM instance profile for Systems Manager • Attach an IAM instance profile to an Amazon EC2 instance 2. Verify that SSM Agent is installed on your EC2 instance. For more information, see Working with SSM Agent on EC2 instances for Windows Server in the AWS Systems Manager User Guide. 3. Verify that the EC2 instance has enough free disk space to download and restore the Microsoft SQL Server backups. Run the Windows to Linux replatforming assistant for SQL Server script This section contains the PowerShell parameter definitions and scripts for replatforming your databases. For more information about how to use PowerShell scripts, see PowerShell. Topics • Replatforming script examples • Replatforming script parameters Prerequisites for replatforming to an existing EC2 instance 77 Microsoft SQL Server on Amazon EC2 User Guide Replatforming script examples The following common scenarios and example PowerShell scripts demonstrate how to replatform your Microsoft SQL Server databases using Windows to Linux replatforming assistant for Microsoft SQL Server Databases. Important The Windows to Linux Replatforming Assistant for Microsoft SQL Server Databases resets the SQL Server server administrator (SA) user password on the target instance every time that it is run. After the replatform process is complete, you must set your own SA user password before you can connect to the target SQL Server instance. Syntax The Windows to Linux replatforming assistant for Microsoft SQL Server Databases script adheres to the syntax shown in the following example. PS C:\> C:\MigrateSQLServerToEC2Linux.ps1 [[-SqlServerInstanceName] <String>] [[- DBNames]<Object[]>] [- MigrateAllDBs] [PathForBackup] <String> [-SetSourceDBModeReadOnly] [- IamInstanceProfileName] <String>[- AWSRegion] <String> [[-EC2InstanceId] <String>] [[-EC2InstanceType] <String>] [[- EC2KeyPair] <String>] [[- SubnetId] <String>] [[-AWSProfileName] <String>] [[-AWSProfileLocation] <String>] [- GeneratePresignedUrls] [<CommonParameters>] Example 1: Move a database to an EC2 instance The following example shows how to move a database named AdventureDB to an EC2 Microsoft SQL Server on Linux instance, with an instance ID of i-024689abcdef, from the Microsoft SQL Server Instance named MSSQLSERVER. The backup directory to be used is D:\\Backup and the AWS Region is us-east-2. PS C:\> ./MigrateSQLServerToEC2Linux.ps1 - SQLServerInstanceName MSSQLSERVER - EC2InstanceId i- 024689abcdef -DBNames AdventureDB -PathForBackup D:\\Backup -AWSRegion us-east-2 - IamInstanceProfileName AmazonSSMManagedInstanceCore Replatforming script examples 78 Microsoft SQL Server on Amazon EC2 User Guide Example 2: Move a database to an EC2 instance using the AWS credentials profile The following example shows how to move the database in Example 1 using the AWS credentials profile: DBMigration. PS C:\> ./MigrateSQLServerToEC2Linux.ps1 - SQLServerInstanceName MSSQLSERVER - EC2InstanceId i- 024689abcdef -DBNames AdventureDB -PathForBackup D:\\Backup -AWSRegion us-east-2 - AWSProfileName DBMigration -IamInstanceProfileName AmazonSSMManagedInstanceCore Example 3: Move a database to a new m5.large type instance The following example shows how to create an m5.large type EC2 Linux instance in subnet- abc127 using the Key Pair customer-ec2-keypair and then moving AdventureDB and TestDB to the new instance from the database used in Examples 1 and 2. PS C:\> ./MigrateSQLServerToEC2Linux.ps1 -EC2InstanceType m5.large -SubnetId subnet- abc127 -EC2KeyPair customer-ec2-keypair -DBNames AdventureDB,TestDB -PathForBackup D:\\Backup - AWSRegion us-east-2 - AWSProfileName DBMigration -IamInstanceProfileName AmazonSSMManagedInstanceCore Example 4: Move all databases to a new m5.large type instance The following example shows how to create an m5.large type EC2 Linux instance in subnet- abc127 using the Key Pair customer-ec2-keypair and then migrating all databases to the instance from databases used in Examples 1 and 2. PS C:\> ./MigrateSQLServerToEC2Linux.ps1 -EC2InstanceType m5.large -SubnetId subnet- abc127 -EC2KeyPair customer-ec2-keypair -MigrateAllDBs -PathForBackup D:\\Backup -AWSRegion us-east-2 - AWSProfileName DBMigration -IamInstanceProfileName AmazonSSMManagedInstanceCore Replatforming script parameters The following parameters are used by the PowerShell script to replatform your Microsoft SQL Server databases. -SqlServerInstanceName Replatforming script parameters 79 Microsoft SQL Server on Amazon EC2 User Guide The name of the Microsoft SQL Server instance to be backed up. If a value for SqlServerInstanceName is not provided, $env:ComputerName is used by default. Type: String Required: No -DBNames The names of the databases to
sql-server-ec2-031
sql-server-ec2.pdf
31
databases to the instance from databases used in Examples 1 and 2. PS C:\> ./MigrateSQLServerToEC2Linux.ps1 -EC2InstanceType m5.large -SubnetId subnet- abc127 -EC2KeyPair customer-ec2-keypair -MigrateAllDBs -PathForBackup D:\\Backup -AWSRegion us-east-2 - AWSProfileName DBMigration -IamInstanceProfileName AmazonSSMManagedInstanceCore Replatforming script parameters The following parameters are used by the PowerShell script to replatform your Microsoft SQL Server databases. -SqlServerInstanceName Replatforming script parameters 79 Microsoft SQL Server on Amazon EC2 User Guide The name of the Microsoft SQL Server instance to be backed up. If a value for SqlServerInstanceName is not provided, $env:ComputerName is used by default. Type: String Required: No -DBNames The names of the databases to be backed up and restored. Specify the names of the databases in a comma-separated list (for example, adventureDB,universityDB). Either the DBNames or MigrateAllDBs parameter is required. Type: Object Required: No -MigrateAllDBs This switch is disabled by default. If this switch is enabled, the automation migrates all databases except for the system databases (master, msdb, tempdb). Either the DBNames or MigrateAllDBs parameter is required. Type: SwitchParameter Required: No -PathForBackup The path where the full backup is stored. Type: String Required: Yes -SetSourceDBModeReadOnly This switch is disabled by default. If this switch is enabled, it makes the database read-only during migration. Type: SwitchParameter Replatforming script parameters 80 Microsoft SQL Server on Amazon EC2 Required: No -IamInstanceProfileName User Guide Enter the AWS IAM instance role with permissions to run Systems Manager Automation on your behalf. See Getting Started with Automation in the AWS Systems Manager User Guide. Type: String Required: Yes -AWSRegion Enter the AWS Region where your Amazon S3 buckets are created to store database backups. Type: String Required: Yes -EC2InstanceId To restore Microsoft SQL Server databases to an existing EC2 instance running Microsoft SQL Server Linux, enter the instance ID of the instance. Make sure that the EC2 instance already has the AWS Systems Manager SSM Agent installed and running. Type: String Required: No -EC2InstanceType To restore Microsoft SQL Server databases to a new EC2 Linux instance, enter the instance type of the instance to be launched. Type: String Required: No -EC2KeyPair To restore Microsoft SQL Server databases to a new EC2 Linux instance, enter the name of the EC2 Key Pair to be used to access the instance. This parameter is recommended if you are creating a new EC2 Linux instance. Replatforming script parameters 81 Microsoft SQL Server on Amazon EC2 User Guide Type: String Required: No -SubnetId This parameter is required when creating a new EC2 Linux instance. When creating a new EC2 Linux instance, if SubnetId is not provided, the AWS user default subnet is used to launch the EC2 Linux instance. Type: String Required: No -AWSProfileName The name of the AWS profile that the automation uses when connecting to AWS services. For more information on the required user permissions, see Getting Started with Automation in the AWS Systems Manager User Guide. If a profile is not entered, the automation uses your default AWS profile. Type: String Required: No -AWSProfileLocation The location of the AWS Profile if the AWS Profile is not stored in the default location. Type: String Required: No -GeneratePresignedUrls This parameter is only used when replatforming to non-EC2 instances, such as to VMware Cloud on AWS or on-premises VMs. Type: SwitchParameter Required: No <CommonParameters> Replatforming script parameters 82 Microsoft SQL Server on Amazon EC2 User Guide This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, see About Common Parameters in the Microsoft PowerShell documentation. Required: No Replatforming script parameters 83 Microsoft SQL Server on Amazon EC2 User Guide Security in Microsoft SQL Server on Amazon EC2 Cloud security at AWS is the highest priority. As an AWS customer, you benefit from a data center and network architecture that is built to meet the requirements of the most security-sensitive organizations. Security is a shared responsibility between AWS and you. The shared responsibility model describes this as security of the cloud and security in the cloud: • Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in the AWS Cloud. AWS also provides you with services that you can use securely. Third- party auditors regularly test and verify the effectiveness of our security as part of the AWS Compliance Programs. To learn about the compliance programs that apply to SQL Server on EC2, see AWS Services in Scope by Compliance Program. • Security in the cloud – Your responsibility is determined by the AWS service that you use. You are also responsible for other factors including the sensitivity of your data, your company’s requirements, and applicable laws and regulations For detailed information about how to configure Amazon EC2 to meet your security and compliance objectives, see Security in Amazon EC2 in the User Guide for Windows Instances. 84 Microsoft SQL
sql-server-ec2-032
sql-server-ec2.pdf
32
of our security as part of the AWS Compliance Programs. To learn about the compliance programs that apply to SQL Server on EC2, see AWS Services in Scope by Compliance Program. • Security in the cloud – Your responsibility is determined by the AWS service that you use. You are also responsible for other factors including the sensitivity of your data, your company’s requirements, and applicable laws and regulations For detailed information about how to configure Amazon EC2 to meet your security and compliance objectives, see Security in Amazon EC2 in the User Guide for Windows Instances. 84 Microsoft SQL Server on Amazon EC2 User Guide Document history for the Microsoft SQL Server on Amazon EC2 User Guide The following table describes the documentation releases for Microsoft SQL Server on Amazon EC2. Change Description Date Database backup and restore with AWS VSS solution based Added support for AWS VSS solution based backup and January 17, 2025 snapshots restore feature. Downgrade your SQL Server edition Added a new section about downgrading your Microsoft August 28, 2023 Migration Initial release SQL Server edition. Added a new section about migrating to Microsoft SQL Server on Amazon EC2. August 1, 2023 Initial release of the Microsoft SQL Server on Amazon EC2 August 18, 2022 User Guide 85
sqs-api-001
sqs-api.pdf
1
API Reference Amazon Simple Queue Service API Version 2012-11-05 Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon Simple Queue Service API Reference Amazon Simple Queue Service: API Reference Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon. Amazon Simple Queue Service Table of Contents API Reference Welcome ........................................................................................................................................... 1 Actions .............................................................................................................................................. 2 AddPermission ............................................................................................................................................... 3 Request Syntax ........................................................................................................................................ 3 Request Parameters ................................................................................................................................ 4 Response Elements ................................................................................................................................. 5 Errors .......................................................................................................................................................... 5 Examples ................................................................................................................................................... 6 See Also ..................................................................................................................................................... 7 CancelMessageMoveTask ............................................................................................................................. 9 Request Syntax ........................................................................................................................................ 9 Request Parameters ................................................................................................................................ 9 Response Syntax ...................................................................................................................................... 9 Response Elements ............................................................................................................................... 10 Errors ....................................................................................................................................................... 10 Examples ................................................................................................................................................. 11 See Also .................................................................................................................................................. 12 ChangeMessageVisibility ........................................................................................................................... 13 Request Syntax ...................................................................................................................................... 14 Request Parameters .............................................................................................................................. 14 Response Elements ............................................................................................................................... 15 Errors ....................................................................................................................................................... 15 Examples ................................................................................................................................................. 16 See Also .................................................................................................................................................. 18 ChangeMessageVisibilityBatch ................................................................................................................. 19 Request Syntax ...................................................................................................................................... 19 Request Parameters .............................................................................................................................. 19 Response Syntax ................................................................................................................................... 20 Response Elements ............................................................................................................................... 20 Errors ....................................................................................................................................................... 21 Examples ................................................................................................................................................. 22 See Also .................................................................................................................................................. 25 CreateQueue ................................................................................................................................................ 26 Request Syntax ...................................................................................................................................... 27 API Version 2012-11-05 iii Amazon Simple Queue Service API Reference Request Parameters .............................................................................................................................. 27 Response Syntax ................................................................................................................................... 32 Response Elements ............................................................................................................................... 32 Errors ....................................................................................................................................................... 32 Examples ................................................................................................................................................. 34 See Also .................................................................................................................................................. 36 DeleteMessage ............................................................................................................................................ 37 Request Syntax ...................................................................................................................................... 37 Request Parameters .............................................................................................................................. 37 Response Elements ............................................................................................................................... 38 Errors ....................................................................................................................................................... 38 Examples ................................................................................................................................................. 39 See Also .................................................................................................................................................. 41 DeleteMessageBatch .................................................................................................................................. 42 Request Syntax ...................................................................................................................................... 42 Request Parameters .............................................................................................................................. 42 Response Syntax ................................................................................................................................... 43 Response Elements ............................................................................................................................... 43 Errors ....................................................................................................................................................... 44 Examples ................................................................................................................................................. 45 See Also .................................................................................................................................................. 47 DeleteQueue ................................................................................................................................................ 49 Request Syntax ...................................................................................................................................... 49 Request Parameters .............................................................................................................................. 49 Response Elements ............................................................................................................................... 50 Errors ....................................................................................................................................................... 50 Examples ................................................................................................................................................. 51 See Also .................................................................................................................................................. 52 GetQueueAttributes ................................................................................................................................... 53 Request Syntax ...................................................................................................................................... 53 Request Parameters .............................................................................................................................. 53 Response Syntax ................................................................................................................................... 57 Response Elements ............................................................................................................................... 58 Errors ....................................................................................................................................................... 58 Examples ................................................................................................................................................. 59 See Also .................................................................................................................................................. 64 API Version 2012-11-05 iv Amazon Simple Queue Service API Reference GetQueueUrl ................................................................................................................................................ 65 Request Syntax ...................................................................................................................................... 65 Request Parameters .............................................................................................................................. 65 Response Syntax ................................................................................................................................... 66 Response Elements ............................................................................................................................... 66 Errors ....................................................................................................................................................... 66 Examples ................................................................................................................................................. 67 See Also .................................................................................................................................................. 68 ListDeadLetterSourceQueues ................................................................................................................... 70 Request Syntax ...................................................................................................................................... 70 Request Parameters .............................................................................................................................. 70 Response Syntax ................................................................................................................................... 71 Response Elements ............................................................................................................................... 71 Errors ....................................................................................................................................................... 72 Examples ................................................................................................................................................. 72 See Also .................................................................................................................................................. 74 ListMessageMoveTasks .............................................................................................................................. 75 Request Syntax ...................................................................................................................................... 75 Request Parameters .............................................................................................................................. 75 Response Syntax ................................................................................................................................... 76 Response Elements ............................................................................................................................... 76 Errors ....................................................................................................................................................... 76 Examples ................................................................................................................................................. 77 See Also .................................................................................................................................................. 79 ListQueues ................................................................................................................................................... 80 Request Syntax ...................................................................................................................................... 80 Request Parameters .............................................................................................................................. 80 Response Syntax ................................................................................................................................... 81 Response Elements ............................................................................................................................... 81 Errors ....................................................................................................................................................... 82 Examples ................................................................................................................................................. 82 See Also .................................................................................................................................................. 84 ListQueueTags ............................................................................................................................................. 86 Request Syntax ...................................................................................................................................... 86 Request Parameters .............................................................................................................................. 86 Response Syntax ................................................................................................................................... 86 API Version 2012-11-05 v Amazon Simple Queue Service API Reference Response Elements ............................................................................................................................... 87 Errors ....................................................................................................................................................... 87 Examples ................................................................................................................................................. 88 See Also .................................................................................................................................................. 89 PurgeQueue ................................................................................................................................................. 91 Request Syntax ...................................................................................................................................... 91 Request Parameters .............................................................................................................................. 91 Response Elements ............................................................................................................................... 92 Errors ....................................................................................................................................................... 92 Examples ................................................................................................................................................. 93 See Also .................................................................................................................................................. 94 ReceiveMessage .......................................................................................................................................... 95 Request Syntax ...................................................................................................................................... 96 Request Parameters .............................................................................................................................. 96 Response Syntax ................................................................................................................................. 102 Response Elements ............................................................................................................................ 102 Errors ..................................................................................................................................................... 102 Examples ............................................................................................................................................... 104 See Also ................................................................................................................................................ 109 RemovePermission ................................................................................................................................... 110 Request Syntax .................................................................................................................................... 110 Request Parameters ........................................................................................................................... 110 Response Elements ............................................................................................................................ 111 Errors ..................................................................................................................................................... 111 Examples ............................................................................................................................................... 112 See Also ................................................................................................................................................ 113 SendMessage ............................................................................................................................................. 114 Request Syntax .................................................................................................................................... 114 Request Parameters ........................................................................................................................... 115 Response Syntax ................................................................................................................................. 119 Response Elements ............................................................................................................................ 119 Errors ..................................................................................................................................................... 120 Examples ............................................................................................................................................... 122 See Also ................................................................................................................................................ 125 SendMessageBatch .................................................................................................................................. 126 Request Syntax .................................................................................................................................... 126 API Version 2012-11-05 vi Amazon Simple Queue Service API Reference Request Parameters ........................................................................................................................... 127 Response Syntax ................................................................................................................................. 128 Response Elements ............................................................................................................................ 128 Errors ..................................................................................................................................................... 129 Examples ............................................................................................................................................... 131 See Also ................................................................................................................................................ 135 SetQueueAttributes ................................................................................................................................. 137 Request Syntax .................................................................................................................................... 137 Request Parameters ........................................................................................................................... 137 Response Elements ............................................................................................................................ 141 Errors ..................................................................................................................................................... 141 Examples ............................................................................................................................................... 143 See Also ................................................................................................................................................ 151 StartMessageMoveTask ........................................................................................................................... 152 Request Syntax .................................................................................................................................... 152 Request Parameters ........................................................................................................................... 152 Response Syntax ................................................................................................................................. 153 Response Elements ............................................................................................................................ 153 Errors ..................................................................................................................................................... 154 Examples ............................................................................................................................................... 154 See Also ................................................................................................................................................ 155 TagQueue ................................................................................................................................................... 157 Request Syntax .................................................................................................................................... 157 Request Parameters ........................................................................................................................... 157 Response Elements ............................................................................................................................ 158 Errors ..................................................................................................................................................... 158 Examples ............................................................................................................................................... 159 See Also ................................................................................................................................................ 160 UntagQueue .............................................................................................................................................. 162 Request Syntax .................................................................................................................................... 162 Request Parameters ........................................................................................................................... 162 Response Elements ............................................................................................................................ 163 Errors ..................................................................................................................................................... 163 Examples ............................................................................................................................................... 163 See Also ................................................................................................................................................
sqs-api-002
sqs-api.pdf
2
Request Syntax .................................................................................................................................... 137 Request Parameters ........................................................................................................................... 137 Response Elements ............................................................................................................................ 141 Errors ..................................................................................................................................................... 141 Examples ............................................................................................................................................... 143 See Also ................................................................................................................................................ 151 StartMessageMoveTask ........................................................................................................................... 152 Request Syntax .................................................................................................................................... 152 Request Parameters ........................................................................................................................... 152 Response Syntax ................................................................................................................................. 153 Response Elements ............................................................................................................................ 153 Errors ..................................................................................................................................................... 154 Examples ............................................................................................................................................... 154 See Also ................................................................................................................................................ 155 TagQueue ................................................................................................................................................... 157 Request Syntax .................................................................................................................................... 157 Request Parameters ........................................................................................................................... 157 Response Elements ............................................................................................................................ 158 Errors ..................................................................................................................................................... 158 Examples ............................................................................................................................................... 159 See Also ................................................................................................................................................ 160 UntagQueue .............................................................................................................................................. 162 Request Syntax .................................................................................................................................... 162 Request Parameters ........................................................................................................................... 162 Response Elements ............................................................................................................................ 163 Errors ..................................................................................................................................................... 163 Examples ............................................................................................................................................... 163 See Also ................................................................................................................................................ 165 Data Types ................................................................................................................................... 166 API Version 2012-11-05 vii Amazon Simple Queue Service API Reference BatchResultErrorEntry ............................................................................................................................. 167 Contents ............................................................................................................................................... 167 See Also ................................................................................................................................................ 167 ChangeMessageVisibilityBatchRequestEntry ...................................................................................... 169 Contents ............................................................................................................................................... 169 See Also ................................................................................................................................................ 169 ChangeMessageVisibilityBatchResultEntry ......................................................................................... 171 Contents ............................................................................................................................................... 171 See Also ................................................................................................................................................ 171 DeleteMessageBatchRequestEntry ....................................................................................................... 172 Contents ............................................................................................................................................... 172 See Also ................................................................................................................................................ 172 DeleteMessageBatchResultEntry ........................................................................................................... 173 Contents ............................................................................................................................................... 173 See Also ................................................................................................................................................ 173 ListMessageMoveTasksResultEntry ....................................................................................................... 174 Contents ............................................................................................................................................... 174 See Also ................................................................................................................................................ 176 Message ...................................................................................................................................................... 177 Contents ............................................................................................................................................... 177 See Also ................................................................................................................................................ 179 MessageAttributeValue ........................................................................................................................... 180 Contents ............................................................................................................................................... 180 See Also ................................................................................................................................................ 181 MessageSystemAttributeValue .............................................................................................................. 182 Contents ............................................................................................................................................... 182 See Also ................................................................................................................................................ 183 SendMessageBatchRequestEntry .......................................................................................................... 184 Contents ............................................................................................................................................... 184 See Also ................................................................................................................................................ 187 SendMessageBatchResultEntry ............................................................................................................. 189 Contents ............................................................................................................................................... 189 See Also ................................................................................................................................................ 190 Common Parameters ................................................................................................................... 191 Common Errors ............................................................................................................................ 194 API Version 2012-11-05 viii Amazon Simple Queue Service API Reference Welcome Welcome to the Amazon SQS API Reference. Amazon SQS is a reliable, highly-scalable hosted queue for storing messages as they travel between applications or microservices. Amazon SQS moves data between distributed application components and helps you decouple these components. For information on the permissions you need to use this API, see Identity and access management in the Amazon SQS Developer Guide. You can use AWS SDKs to access Amazon SQS using your favorite programming language. The SDKs perform tasks such as the following automatically: • Cryptographically sign your service requests • Retry requests • Handle error responses Additional information • Amazon SQS Product Page • Amazon SQS Developer Guide • Making API Requests • Amazon SQS Message Attributes • Amazon SQS Dead-Letter Queues • Amazon SQS in the AWS Command Line Interface • Amazon Web Services General Reference • Regions and Endpoints This document was last published on May 14, 2025. API Version 2012-11-05 1 Amazon Simple Queue Service API Reference Actions The following actions are supported: • AddPermission • CancelMessageMoveTask • ChangeMessageVisibility • ChangeMessageVisibilityBatch • CreateQueue • DeleteMessage • DeleteMessageBatch • DeleteQueue • GetQueueAttributes • GetQueueUrl • ListDeadLetterSourceQueues • ListMessageMoveTasks • ListQueues • ListQueueTags • PurgeQueue • ReceiveMessage • RemovePermission • SendMessage • SendMessageBatch • SetQueueAttributes • StartMessageMoveTask • TagQueue • UntagQueue API Version 2012-11-05 2 Amazon Simple Queue Service AddPermission API Reference Adds a permission to a queue for a specific principal. This allows sharing access to the queue. When you create a queue, you have full control access rights for the queue. Only you, the owner of the queue, can grant or deny permissions to the queue. For more information about these permissions, see Allow Developers to Write Messages to a Shared Queue in the Amazon SQS Developer Guide. Note • AddPermission generates a policy for you. You can use SetQueueAttributes to upload your policy. For more information, see Using Custom Policies with the Amazon SQS Access Policy Language in the Amazon SQS Developer Guide. • An Amazon SQS policy can have a maximum of seven actions per statement. • To remove the ability to change queue permissions, you must deny permission to the AddPermission, RemovePermission, and SetQueueAttributes actions in your IAM policy. • Amazon SQS AddPermission does not support adding a non-account principal. Note Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. Request Syntax { "Actions": [ "string" ], "AWSAccountIds": [ "string" ], "Label": "string", "QueueUrl": "string" } AddPermission API Version 2012-11-05 3 Amazon Simple Queue Service Request Parameters API Reference For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. Actions The action the client wants to allow for the specified principal. Valid values: the name of any action or *. For more information about these actions, see Overview of Managing Access Permissions to Your Amazon Simple Queue Service Resource in the Amazon SQS Developer Guide. Specifying SendMessage, DeleteMessage, or ChangeMessageVisibility for ActionName.n also grants permissions for the corresponding batch versions of those actions: SendMessageBatch, DeleteMessageBatch, and ChangeMessageVisibilityBatch. Type: Array of strings Required: Yes AWSAccountIds The AWS account numbers of the principals who are to receive permission. For information about locating the AWS account identification, see Your AWS Identifiers in
sqs-api-003
sqs-api.pdf
3
Actions The action the client wants to allow for the specified principal. Valid values: the name of any action or *. For more information about these actions, see Overview of Managing Access Permissions to Your Amazon Simple Queue Service Resource in the Amazon SQS Developer Guide. Specifying SendMessage, DeleteMessage, or ChangeMessageVisibility for ActionName.n also grants permissions for the corresponding batch versions of those actions: SendMessageBatch, DeleteMessageBatch, and ChangeMessageVisibilityBatch. Type: Array of strings Required: Yes AWSAccountIds The AWS account numbers of the principals who are to receive permission. For information about locating the AWS account identification, see Your AWS Identifiers in the Amazon SQS Developer Guide. Type: Array of strings Required: Yes Label The unique identification of the permission you're setting (for example, AliceSendMessage). Maximum 80 characters. Allowed characters include alphanumeric characters, hyphens (-), and underscores (_). Type: String Required: Yes QueueUrl The URL of the Amazon SQS queue to which permissions are added. Request Parameters API Version 2012-11-05 4 Amazon Simple Queue Service API Reference Queue URLs and names are case-sensitive. Type: String Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 OverLimit The specified action violates a limit. For example, ReceiveMessage returns this error if the maximum number of in flight messages is reached and AddPermission returns this error if the maximum number of permissions for the queue is reached. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. Response Elements API Version 2012-11-05 5 Amazon Simple Queue Service API Reference • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following example query requests grant a SendMessage permission to the principal whose AWS account number is 177715257436 and a ReceiveMessage permission to the principal whose AWS account number is 111111111111. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.AddPermission X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Label": "MyLabel", "Actions": ["SendMessage", "ReceiveMessage"], "AWSAccountIds": ["177715257436", "111111111111"] } Examples API Version 2012-11-05 6 API Reference Amazon Simple Queue Service Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: 0 Date: <Date> Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=AddPermission &Label=MyLabel &AWSAccountId.1=177715257436 &ActionName.1=SendMessage &AWSAccountId.2=111111111111 &ActionName.2=ReceiveMessage Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <AddPermissionResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>b05e862e-c961-5213-bd8d-da5e6667b7d7</RequestId> </ResponseMetadata> </AddPermissionResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: See Also API Version 2012-11-05 7 API Reference Amazon Simple Queue Service • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 8 Amazon Simple Queue Service API Reference CancelMessageMoveTask Cancels a specified message movement task. A message movement can only be cancelled when the current status is RUNNING. Cancelling a message movement task does not revert the messages that have already been moved. It can only stop the messages that have not been moved yet. Note • This action is currently limited to supporting message redrive from dead-letter queues (DLQs) only. In this context, the source queue is the dead-letter queue (DLQ), while the destination queue can be the original source queue (from which the messages were driven to the dead-letter-queue), or a custom destination queue. • Only one active message movement task is supported per queue at any given time. Request Syntax { "TaskHandle": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. TaskHandle An identifier associated with a message movement task. Type: String Required: Yes Response Syntax {
sqs-api-004
sqs-api.pdf
4
queues (DLQs) only. In this context, the source queue is the dead-letter queue (DLQ), while the destination queue can be the original source queue (from which the messages were driven to the dead-letter-queue), or a custom destination queue. • Only one active message movement task is supported per queue at any given time. Request Syntax { "TaskHandle": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. TaskHandle An identifier associated with a message movement task. Type: String Required: Yes Response Syntax { CancelMessageMoveTask API Version 2012-11-05 9 Amazon Simple Queue Service API Reference "ApproximateNumberOfMessagesMoved": number } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. ApproximateNumberOfMessagesMoved The approximate number of messages already moved to the destination queue. Type: Long Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 ResourceNotFoundException One or more specified resources don't exist. Response Elements API Version 2012-11-05 10 API Reference Amazon Simple Queue Service HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples Example Using AWS query protocol The following example query cancels an existing running message move task. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=CancelMessageMoveTask &TaskHandle=eyJ0YXNrSWQiOiJkYzE2OWUwNC0wZTU1LTQ0ZDItYWE5MC1jMDgwY2ExZjM2ZjciLCJzb3VyY2VBcm4iOiJhcm46YXdzOnNxczp1cy1lYXN0LTE6MTc3NzE1MjU3NDM2Ok15RGVhZExldHRlclF1ZXVlIn0= Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <CancelMessageMoveTaskResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <CancelMessageMoveTaskResult> <ApproximateNumberOfMessagesMoved>300</ApproximateNumberOfMessagesMoved> </CancelMessageMoveTaskResult> <ResponseMetadata> <RequestId>9b20926c-8b35-5d8e-9559-ce1c22e754dc</RequestId> </ResponseMetadata> </CancelMessageMoveTaskResponse> Examples API Version 2012-11-05 11 Amazon Simple Queue Service See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 12 Amazon Simple Queue Service API Reference ChangeMessageVisibility Changes the visibility timeout of a specified message in a queue to a new value. The default visibility timeout for a message is 30 seconds. The minimum is 0 seconds. The maximum is 12 hours. For more information, see Visibility Timeout in the Amazon SQS Developer Guide. For example, if the default timeout for a queue is 60 seconds, 15 seconds have elapsed since you received the message, and you send a ChangeMessageVisibility call with VisibilityTimeout set to 10 seconds, the 10 seconds begin to count from the time that you make the ChangeMessageVisibility call. Thus, any attempt to change the visibility timeout or to delete that message 10 seconds after you initially change the visibility timeout (a total of 25 seconds) might result in an error. An Amazon SQS message has three basic states: 1. Sent to a queue by a producer. 2. Received from the queue by a consumer. 3. Deleted from the queue. A message is considered to be stored after it is sent to a queue by a producer, but not yet received from the queue by a consumer (that is, between states 1 and 2). There is no limit to the number of stored messages. A message is considered to be in flight after it is received from a queue by a consumer, but not yet deleted from the queue (that is, between states 2 and 3). There is a limit to the number of in flight messages. Limits that apply to in flight messages are unrelated to the unlimited number of stored messages. For most standard queues (depending on queue traffic and message backlog), there can be a maximum of approximately 120,000 in flight messages (received from a queue by a consumer, but not yet deleted from the queue). If you reach this limit, Amazon SQS returns the OverLimit error message. To avoid reaching the limit, you should delete messages from the queue after they're processed. You can also increase the number of queues you use to
sqs-api-005
sqs-api.pdf
5
is a limit to the number of in flight messages. Limits that apply to in flight messages are unrelated to the unlimited number of stored messages. For most standard queues (depending on queue traffic and message backlog), there can be a maximum of approximately 120,000 in flight messages (received from a queue by a consumer, but not yet deleted from the queue). If you reach this limit, Amazon SQS returns the OverLimit error message. To avoid reaching the limit, you should delete messages from the queue after they're processed. You can also increase the number of queues you use to process your messages. To request a limit increase, file a support request. For FIFO queues, there can be a maximum of 120,000 in flight messages (received from a queue by a consumer, but not yet deleted from the queue). If you reach this limit, Amazon SQS returns no error messages. ChangeMessageVisibility API Version 2012-11-05 13 Amazon Simple Queue Service API Reference Important If you attempt to set the VisibilityTimeout to a value greater than the maximum time left, Amazon SQS returns an error. Amazon SQS doesn't automatically recalculate and increase the timeout to the maximum remaining time. Unlike with a queue, when you change the visibility timeout for a specific message the timeout value is applied immediately but isn't saved in memory for that message. If you don't delete a message after it is received, the visibility timeout for the message reverts to the original timeout value (not to the value you set using the ChangeMessageVisibility action) the next time the message is received. Request Syntax { "QueueUrl": "string", "ReceiptHandle": "string", "VisibilityTimeout": number } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. QueueUrl The URL of the Amazon SQS queue whose message's visibility is changed. Queue URLs and names are case-sensitive. Type: String Required: Yes ReceiptHandle The receipt handle associated with the message, whose visibility timeout is changed. This parameter is returned by the ReceiveMessage action. Request Syntax API Version 2012-11-05 14 Amazon Simple Queue Service Type: String Required: Yes VisibilityTimeout API Reference The new value for the message's visibility timeout (in seconds). Values range: 0 to 43200. Maximum: 12 hours. Type: Integer Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 MessageNotInflight The specified message isn't in flight. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 Response Elements API Version 2012-11-05 15 Amazon Simple Queue Service ReceiptHandleIsInvalid The specified receipt handle isn't valid. HTTP Status Code: 400 RequestThrottled API Reference The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following example queries request changes the visibility timeout for a message to 60 seconds. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.ChangeMessageVisibility X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { Examples API Version 2012-11-05 16 Amazon Simple Queue Service API Reference "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "ReceiptHandle": "AQEBaZ+j5qUoOAoxlmrCQPkBm9njMWXqemmIG6shMHCO6fV20JrQYg/ AiZ8JELwLwOu5U61W+aIX5Qzu7GGofxJuvzymr4Ph53RiR0mudj4InLSgpSspYeTRDteBye5tV/txbZDdNZxsi +qqZA9xPnmMscKQqF6pGhnGIKrnkYGl45Nl6GPIZv62LrIRb6mSqOn1fn0yqrvmWuuY3w2UzQbaYunJWGxpzZze21EOBtywknU3Je/ g7G9is +c6K9hGniddzhLkK1tHzZKjejOU4jokaiB4nmi0dF3JqLzDsQuPF0Gi8qffhEvw56nl8QCbluSJScFhJYvoagGnDbwOnd9z50L239qtFIgETdpKyirlWwl/ NGjWJ45dqWpiW3d2Ws7q", "VisibilityTimeout": 60 } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: 0 Date: <Date> Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=ChangeMessageVisibility &VisibilityTimeout=60 &ReceiptHandle=AQEBwPTK2fT2gy97H1iyU5in9umgT+Y4IOxyKGOzpZa8iemEqoR5/ aPn0xAodmiVTzyrW7S4e8XwcWbB04XK92jIQzUpiGwRFA4Dl7r3GOw84Qzq/0OBQe/ JaKxJw6iilafYA5fo1SJQo5Wg8xXbJHTVlJqgvTXd/ UtlByLMhWMi0JMra1UUjYiPsGtYUpLVnOaRkYSPvzRnFFYUbcqCW9lm2BijQKK6KNOZyCCfIh8TooE5i4P2L9N3o9yUHwMdv6p0nb5lKaGurQ2sJwwsyhXf38ZHnVN6pWwsqQnWKYuEXpxPofxd2lcLdgUurMpydS22DzCrkAaf6gmrdxbmCAoeQxE0sFf8alwX9yQmcOjny9aLGe7ro4Vl5o5KMr5hHM4vHEyhwi4wHeKM6MGX0vATA== Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> Examples API Version 2012-11-05 17 Amazon Simple Queue Service API Reference <ChangeMessageVisibilityResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>6a7a282a-d013-4a59-aba9-335b0fa48bed</RequestId> </ResponseMetadata> </ChangeMessageVisibilityResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also
sqs-api-006
sqs-api.pdf
6
Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> Examples API Version 2012-11-05 17 Amazon Simple Queue Service API Reference <ChangeMessageVisibilityResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>6a7a282a-d013-4a59-aba9-335b0fa48bed</RequestId> </ResponseMetadata> </ChangeMessageVisibilityResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 18 Amazon Simple Queue Service API Reference ChangeMessageVisibilityBatch Changes the visibility timeout of multiple messages. This is a batch version of ChangeMessageVisibility. The result of the action on each message is reported individually in the response. You can send up to 10 ChangeMessageVisibility requests with each ChangeMessageVisibilityBatch action. Important Because the batch request can result in a combination of successful and unsuccessful actions, you should check for batch errors even when the call returns an HTTP status code of 200. Request Syntax { "Entries": [ { "Id": "string", "ReceiptHandle": "string", "VisibilityTimeout": number } ], "QueueUrl": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. Entries Lists the receipt handles of the messages for which the visibility timeout must be changed. Type: Array of ChangeMessageVisibilityBatchRequestEntry objects Required: Yes ChangeMessageVisibilityBatch API Version 2012-11-05 19 Amazon Simple Queue Service QueueUrl API Reference The URL of the Amazon SQS queue whose messages' visibility is changed. Queue URLs and names are case-sensitive. Type: String Required: Yes Response Syntax { "Failed": [ { "Code": "string", "Id": "string", "Message": "string", "SenderFault": boolean } ], "Successful": [ { "Id": "string" } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Failed A list of BatchResultErrorEntry items. Type: Array of BatchResultErrorEntry objects Successful A list of ChangeMessageVisibilityBatchResultEntry items. Response Syntax API Version 2012-11-05 20 Amazon Simple Queue Service API Reference Type: Array of ChangeMessageVisibilityBatchResultEntry objects Errors For information about the errors that are common to all actions, see Common Errors. BatchEntryIdsNotDistinct Two or more batch entries in the request have the same Id. HTTP Status Code: 400 EmptyBatchRequest The batch request doesn't contain any entries. HTTP Status Code: 400 InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidBatchEntryId The Id of a batch entry in a batch request doesn't abide by the specification. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. Errors API Version 2012-11-05 21 Amazon Simple Queue Service API Reference • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 TooManyEntriesInBatchRequest The batch request contains more entries than permissible. For Amazon SQS, the maximum number of entries you can include in a single SendMessageBatch, DeleteMessageBatch, or ChangeMessageVisibilityBatch request is 10. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples ChangeMessageVisibilityBatch request changes the visibility timeout settings for two messages. You must URL-encode the entire URL. However, in this example only the message body is URL-encoded to make the example easier to read. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.ChangeMessageVisibilityBatch X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", Examples API Version 2012-11-05 22 Amazon Simple Queue Service "Entries": [ { "Id": "change_visibility_msg_1", API Reference "ReceiptHandle": "AQEBt7JdeB+HGhLUgVF4/Gc+AvTPvgUL +AVpoHQPb3Gw9U6bRBxx4KYy3U5bk+hBLDGAj84UxMMTG1uhCJLMuS+5MrRkuEE0pgJr6B6J12Xk +qstDQNsRuamy21kSzjmDWhdKNexq8mcMy8dbmSYLa +GytNMShSzyOhrBBUbcwkTdbJPW9czNs6nR4Wb8CteMPwzYCYrYHaM/ tePfqcMwlq+d7PSXTM965g2DrTP5pF5puB00BA5MkHTkZyMkUZyENTS704HH +uZW06+7IWUTPcBma8aFt8MY0eeDnOhBtM8SD6fcnNxHXHDOmSkE6cpA68ew5wwYkPdQ2U341SxJbNWGPEfmzCtRJKs7Mc3J +cdjfyNR3QzXiVucoqS6mmRDnVe", "VisibilityTimeout": 45 }, { "Id": "change_visibility_msg_2", "ReceiptHandle": "AQEB3LQoW7GQWgodQCEJXHjMvO/QkeCHiRldRfLC/E6RUggm +BjpthqxfoUOUn6Vs271qmrBaufFqEmnMKgk2n1EuUBne1pe+hZcrDE8IveUUPmqkUT54FGhAAjPX3oEIryz/ XeQ/muKAuLclcZvt2Q+ZDPW8DvZqMa1RoHxOqSq+6kQ4PwgQxB+VqDYvIc/LpHOoL4PTROBXgLPjWrzz/ knK6HTzKpqC4ESvFdJ/dkk2nvS0iqYOly5VQknK/lv/rTUOgEYevjJSrNLIPDgZGyvgcLwbm6+yo1cW/ c9cPDiVm96gIhVkuiCZ1gtskoOtyroZVPcY71clDG2EPZJeY8akMd3u+sXEMWhiOPFs1cgWQs2ugsL +vdwMCbsZRkXbJv7", "VisibilityTimeout": 45 } ] } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "Failed": [], "Successful": [ { "Id": "change_visibility_msg_1" }, { "Id": "change_visibility_msg_2" } ] } Examples API Version 2012-11-05 23 API Reference Amazon Simple Queue Service Example Using AWS query protocol Sample Request POST /177715257436/MyQueue HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=ChangeMessageVisibilityBatch &ChangeMessageVisibilityBatchRequestEntry.1.Id=change_visibility_msg_2 &ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle=gfk0T0R0waama4fVFffkjKzmhMCymjQvfTFk2LxT33G4ms5subrE0deLKWSscPU1oD3J9zgeS4PQQ3U30qOumIE6AdAv3w %2F%2Fa1IXW6AqaWhGsEPaLm3Vf6IiWqdM8u5imB%2BNTwj3tQRzOWdTOePjOjPcTpRxBtXix %2BEvwJOZUma9wabv%2BSw6ZHjwmNcVDx8dZXJhVp16Bksiox %2FGrUvrVTCJRTWTLc59oHLLF8sEkKzRmGNzTDGTiV %2BYjHfQj60FD3rVaXmzTsoNxRhKJ72uIHVMGVQiAGgBX6HGv 9LDmYhPXw4hy%2FNgIg%3D%3D &ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout=45 &ChangeMessageVisibilityBatchRequestEntry.2.Id=change_visibility_msg_3 &ChangeMessageVisibilityBatchRequestEntry.2.ReceiptHandle=gfk0T0R0waama4f VFffkjKzmhMCymjQvfTFk2LxT33FUgBz3%2BnougdeLKWSscPU1%2FXgx%2BxcNnjnQQ3U30q OumIE6AdAv3w%2F%2Fa1IXW6AqaWhGsEPaLm3Vf6IiWqdM8u5imB%2BNTwj3tQRzOWdTOePjO sogjZM%2F7kzn4Ew27XLU9I%2FYaWYmKvDbq%2Fk3HKVB9HfB43kE49atP2aWrzNL4yunG41Q 4cfRRtfJdcGQGNHQ2%2Byd0Usf5qR1dZr1iDo5xk946eQat83AxTRP%2BY4Qi0V7FAeSLH9su 9xpX6HGv9LDmYhPXw4hy%2FNgIg%3D%3D &ChangeMessageVisibilityBatchRequestEntry.2.VisibilityTimeout=45 Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <ChangeMessageVisibilityBatchResponse xmlns="http://queue.amazonaws.com/ doc/2012-11-05/"> <ChangeMessageVisibilityBatchResult> <ChangeMessageVisibilityBatchResultEntry> <Id>change_visibility_msg_2</Id> </ChangeMessageVisibilityBatchResultEntry> <ChangeMessageVisibilityBatchResultEntry> <Id>change_visibility_msg_3</Id> </ChangeMessageVisibilityBatchResultEntry> Examples API Version 2012-11-05 24 Amazon Simple Queue Service API Reference
sqs-api-007
sqs-api.pdf
7
<requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "Failed": [], "Successful": [ { "Id": "change_visibility_msg_1" }, { "Id": "change_visibility_msg_2" } ] } Examples API Version 2012-11-05 23 API Reference Amazon Simple Queue Service Example Using AWS query protocol Sample Request POST /177715257436/MyQueue HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=ChangeMessageVisibilityBatch &ChangeMessageVisibilityBatchRequestEntry.1.Id=change_visibility_msg_2 &ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle=gfk0T0R0waama4fVFffkjKzmhMCymjQvfTFk2LxT33G4ms5subrE0deLKWSscPU1oD3J9zgeS4PQQ3U30qOumIE6AdAv3w %2F%2Fa1IXW6AqaWhGsEPaLm3Vf6IiWqdM8u5imB%2BNTwj3tQRzOWdTOePjOjPcTpRxBtXix %2BEvwJOZUma9wabv%2BSw6ZHjwmNcVDx8dZXJhVp16Bksiox %2FGrUvrVTCJRTWTLc59oHLLF8sEkKzRmGNzTDGTiV %2BYjHfQj60FD3rVaXmzTsoNxRhKJ72uIHVMGVQiAGgBX6HGv 9LDmYhPXw4hy%2FNgIg%3D%3D &ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout=45 &ChangeMessageVisibilityBatchRequestEntry.2.Id=change_visibility_msg_3 &ChangeMessageVisibilityBatchRequestEntry.2.ReceiptHandle=gfk0T0R0waama4f VFffkjKzmhMCymjQvfTFk2LxT33FUgBz3%2BnougdeLKWSscPU1%2FXgx%2BxcNnjnQQ3U30q OumIE6AdAv3w%2F%2Fa1IXW6AqaWhGsEPaLm3Vf6IiWqdM8u5imB%2BNTwj3tQRzOWdTOePjO sogjZM%2F7kzn4Ew27XLU9I%2FYaWYmKvDbq%2Fk3HKVB9HfB43kE49atP2aWrzNL4yunG41Q 4cfRRtfJdcGQGNHQ2%2Byd0Usf5qR1dZr1iDo5xk946eQat83AxTRP%2BY4Qi0V7FAeSLH9su 9xpX6HGv9LDmYhPXw4hy%2FNgIg%3D%3D &ChangeMessageVisibilityBatchRequestEntry.2.VisibilityTimeout=45 Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <ChangeMessageVisibilityBatchResponse xmlns="http://queue.amazonaws.com/ doc/2012-11-05/"> <ChangeMessageVisibilityBatchResult> <ChangeMessageVisibilityBatchResultEntry> <Id>change_visibility_msg_2</Id> </ChangeMessageVisibilityBatchResultEntry> <ChangeMessageVisibilityBatchResultEntry> <Id>change_visibility_msg_3</Id> </ChangeMessageVisibilityBatchResultEntry> Examples API Version 2012-11-05 24 Amazon Simple Queue Service API Reference </ChangeMessageVisibilityBatchResult> <ResponseMetadata> <RequestId>ca9668f7-ab1b-4f7a-8859-f15747ab17a7</RequestId> </ResponseMetadata> </ChangeMessageVisibilityBatchResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 25 Amazon Simple Queue Service CreateQueue API Reference Creates a new standard or FIFO queue. You can pass one or more attributes in the request. Keep the following in mind: • If you don't specify the FifoQueue attribute, Amazon SQS creates a standard queue. Note You can't change the queue type after you create it and you can't convert an existing standard queue into a FIFO queue. You must either create a new FIFO queue for your application or delete your existing standard queue and recreate it as a FIFO queue. For more information, see Moving From a Standard Queue to a FIFO Queue in the Amazon SQS Developer Guide. • If you don't provide a value for an attribute, the queue is created with the default value for the attribute. • If you delete a queue, you must wait at least 60 seconds before creating a queue with the same name. To successfully create a new queue, you must provide a queue name that adheres to the limits related to queues and is unique within the scope of your queues. Note After you create a queue, you must wait at least one second after the queue is created to be able to use the queue. To retrieve the URL of a queue, use the GetQueueUrl action. This action only requires the QueueName parameter. When creating queues, keep the following points in mind: • If you specify the name of an existing queue and provide the exact same names and values for all its attributes, the CreateQueue action will return the URL of the existing queue instead of creating a new one. CreateQueue API Version 2012-11-05 26 Amazon Simple Queue Service API Reference • If you attempt to create a queue with a name that already exists but with different attribute names or values, the CreateQueue action will return an error. This ensures that existing queues are not inadvertently altered. Note Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. Request Syntax { "Attributes": { "string" : "string" }, "QueueName": "string", "tags": { "string" : "string" } } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. Attributes A map of attributes with their corresponding values. The following lists the names, descriptions, and values of the special request parameters that the CreateQueue action uses: • DelaySeconds – The length of time, in seconds, for which the delivery of all messages in the queue is delayed. Valid values: An integer from 0 to 900 seconds (15 minutes). Default: 0. • MaximumMessageSize – The limit of how many bytes a message can contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes (1 KiB) to 262,144 bytes (256 KiB). Default: 262,144 (256 KiB). Request Syntax API Version 2012-11-05 27 Amazon Simple Queue Service API Reference • MessageRetentionPeriod – The length of time, in seconds, for which Amazon SQS retains a message. Valid values: An integer from 60 seconds (1 minute) to 1,209,600 seconds (14 days). Default: 345,600 (4 days). When you change a queue's attributes, the change can take up to 60 seconds for most of the attributes to propagate throughout the Amazon SQS system. Changes made to the MessageRetentionPeriod attribute can take up to 15 minutes and will impact existing messages in the queue potentially causing them to be expired and deleted if the MessageRetentionPeriod is reduced below the age of existing messages. • Policy – The queue's policy. A valid AWS policy. For more information about policy structure, see Overview
sqs-api-008
sqs-api.pdf
8
values: An integer from 60 seconds (1 minute) to 1,209,600 seconds (14 days). Default: 345,600 (4 days). When you change a queue's attributes, the change can take up to 60 seconds for most of the attributes to propagate throughout the Amazon SQS system. Changes made to the MessageRetentionPeriod attribute can take up to 15 minutes and will impact existing messages in the queue potentially causing them to be expired and deleted if the MessageRetentionPeriod is reduced below the age of existing messages. • Policy – The queue's policy. A valid AWS policy. For more information about policy structure, see Overview of AWS IAM Policies in the IAM User Guide. • ReceiveMessageWaitTimeSeconds – The length of time, in seconds, for which a ReceiveMessage action waits for a message to arrive. Valid values: An integer from 0 to 20 (seconds). Default: 0. • VisibilityTimeout – The visibility timeout for the queue, in seconds. Valid values: An integer from 0 to 43,200 (12 hours). Default: 30. For more information about the visibility timeout, see Visibility Timeout in the Amazon SQS Developer Guide. The following attributes apply only to dead-letter queues: • RedrivePolicy – The string that includes the parameters for the dead-letter queue functionality of the source queue as a JSON object. The parameters are as follows: • deadLetterTargetArn – The Amazon Resource Name (ARN) of the dead-letter queue to which Amazon SQS moves messages after the value of maxReceiveCount is exceeded. • maxReceiveCount – The number of times a message is delivered to the source queue before being moved to the dead-letter queue. Default: 10. When the ReceiveCount for a message exceeds the maxReceiveCount for a queue, Amazon SQS moves the message to the dead-letter-queue. • RedriveAllowPolicy – The string that includes the parameters for the permissions for the dead-letter queue redrive permission and which source queues can specify dead-letter queues as a JSON object. The parameters are as follows: • redrivePermission – The permission type that defines which source queues can specify the current queue as the dead-letter queue. Valid values are: • allowAll – (Default) Any source queues in this AWS account in the same Region can specify this queue as the dead-letter queue. • denyAll – No source queues can specify this queue as the dead-letter queue. Request Parameters API Version 2012-11-05 28 Amazon Simple Queue Service API Reference • byQueue – Only queues specified by the sourceQueueArns parameter can specify this queue as the dead-letter queue. • sourceQueueArns – The Amazon Resource Names (ARN)s of the source queues that can specify this queue as the dead-letter queue and redrive messages. You can specify this parameter only when the redrivePermission parameter is set to byQueue. You can specify up to 10 source queue ARNs. To allow more than 10 source queues to specify dead- letter queues, set the redrivePermission parameter to allowAll. Note The dead-letter queue of a FIFO queue must also be a FIFO queue. Similarly, the dead- letter queue of a standard queue must also be a standard queue. The following attributes apply only to server-side-encryption: • KmsMasterKeyId – The ID of an AWS managed customer master key (CMK) for Amazon SQS or a custom CMK. For more information, see Key Terms. While the alias of the AWS managed CMK for Amazon SQS is always alias/aws/sqs, the alias of a custom CMK can, for example, be alias/MyAlias . For more examples, see KeyId in the AWS Key Management Service API Reference. • KmsDataKeyReusePeriodSeconds – The length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. An integer representing seconds, between 60 seconds (1 minute) and 86,400 seconds (24 hours). Default: 300 (5 minutes). A shorter time period provides better security but results in more calls to KMS which might incur charges after Free Tier. For more information, see How Does the Data Key Reuse Period Work? • SqsManagedSseEnabled – Enables server-side queue encryption using SQS owned encryption keys. Only one server-side encryption option is supported per queue (for example, SSE-KMS or SSE-SQS). The following attributes apply only to FIFO (first-in-first-out) queues: • FifoQueue – Designates a queue as FIFO. Valid values are true and false. If you don't specify the FifoQueue attribute, Amazon SQS creates a standard queue. You can provide this attribute only during queue creation. You can't change it for an existing queue. When you set this attribute, you must also provide the MessageGroupId for your messages explicitly. For more information, see FIFO queue logic in the Amazon SQS Developer Guide. Request Parameters API Version 2012-11-05 29 Amazon Simple Queue Service API Reference • ContentBasedDeduplication – Enables content-based deduplication. Valid values are true and false. For more information, see Exactly-once processing in the Amazon SQS Developer Guide. Note the following: •
sqs-api-009
sqs-api.pdf
9
and false. If you don't specify the FifoQueue attribute, Amazon SQS creates a standard queue. You can provide this attribute only during queue creation. You can't change it for an existing queue. When you set this attribute, you must also provide the MessageGroupId for your messages explicitly. For more information, see FIFO queue logic in the Amazon SQS Developer Guide. Request Parameters API Version 2012-11-05 29 Amazon Simple Queue Service API Reference • ContentBasedDeduplication – Enables content-based deduplication. Valid values are true and false. For more information, see Exactly-once processing in the Amazon SQS Developer Guide. Note the following: • Every message must have a unique MessageDeduplicationId. • You may provide a MessageDeduplicationId explicitly. • If you aren't able to provide a MessageDeduplicationId and you enable ContentBasedDeduplication for your queue, Amazon SQS uses a SHA-256 hash to generate the MessageDeduplicationId using the body of the message (but not the attributes of the message). • If you don't provide a MessageDeduplicationId and the queue doesn't have ContentBasedDeduplication set, the action fails with an error. • If the queue has ContentBasedDeduplication set, your MessageDeduplicationId overrides the generated one. • When ContentBasedDeduplication is in effect, messages with identical content sent within the deduplication interval are treated as duplicates and only one copy of the message is delivered. • If you send one message with ContentBasedDeduplication enabled and then another message with a MessageDeduplicationId that is the same as the one generated for the first MessageDeduplicationId, the two messages are treated as duplicates and only one copy of the message is delivered. The following attributes apply only to high throughput for FIFO queues: • DeduplicationScope – Specifies whether message deduplication occurs at the message group or queue level. Valid values are messageGroup and queue. • FifoThroughputLimit – Specifies whether the FIFO queue throughput quota applies to the entire queue or per message group. Valid values are perQueue and perMessageGroupId. The perMessageGroupId value is allowed only when the value for DeduplicationScope is messageGroup. To enable high throughput for FIFO queues, do the following: • Set DeduplicationScope to messageGroup. • Set FifoThroughputLimit to perMessageGroupId. If you set these attributes to anything other than the values shown for enabling high throughput, normal throughput is in effect and deduplication occurs as specified. Request Parameters API Version 2012-11-05 30 Amazon Simple Queue Service API Reference For information on throughput quotas, see Quotas related to messages in the Amazon SQS Developer Guide. Type: String to string map Valid Keys: All | Policy | VisibilityTimeout | MaximumMessageSize | MessageRetentionPeriod | ApproximateNumberOfMessages | ApproximateNumberOfMessagesNotVisible | CreatedTimestamp | LastModifiedTimestamp | QueueArn | ApproximateNumberOfMessagesDelayed | DelaySeconds | ReceiveMessageWaitTimeSeconds | RedrivePolicy | FifoQueue | ContentBasedDeduplication | KmsMasterKeyId | KmsDataKeyReusePeriodSeconds | DeduplicationScope | FifoThroughputLimit | RedriveAllowPolicy | SqsManagedSseEnabled Required: No QueueName The name of the new queue. The following limits apply to this name: • A queue name can have up to 80 characters. • Valid values: alphanumeric characters, hyphens (-), and underscores (_). • A FIFO queue name must end with the .fifo suffix. Queue URLs and names are case-sensitive. Type: String Required: Yes tags Add cost allocation tags to the specified Amazon SQS queue. For an overview, see Tagging Your Amazon SQS Queues in the Amazon SQS Developer Guide. When you use queue tags, keep the following guidelines in mind: • Adding more than 50 tags to a queue isn't recommended. • Tags don't have any semantic meaning. Amazon SQS interprets tags as character strings. • Tags are case-sensitive. • A new tag with a key identical to that of an existing tag overwrites the existing tag. Request Parameters API Version 2012-11-05 31 Amazon Simple Queue Service API Reference For a full list of tag restrictions, see Quotas related to queues in the Amazon SQS Developer Guide. Note To be able to tag a queue on creation, you must have the sqs:CreateQueue and sqs:TagQueue permissions. Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. Type: String to string map Required: No Response Syntax { "QueueUrl": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. QueueUrl The URL of the created Amazon SQS queue. Type: String Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. Response Syntax API Version 2012-11-05 32 API Reference Amazon Simple Queue Service HTTP Status Code: 400 InvalidAttributeName The specified attribute doesn't exist. HTTP Status Code: 400 InvalidAttributeValue A queue attribute value is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDeletedRecently You must wait 60 seconds
sqs-api-010
sqs-api.pdf
10
in JSON format by the service. QueueUrl The URL of the created Amazon SQS queue. Type: String Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. Response Syntax API Version 2012-11-05 32 API Reference Amazon Simple Queue Service HTTP Status Code: 400 InvalidAttributeName The specified attribute doesn't exist. HTTP Status Code: 400 InvalidAttributeValue A queue attribute value is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDeletedRecently You must wait 60 seconds after deleting a queue before you can create another queue with the same name. HTTP Status Code: 400 QueueNameExists A queue with this name already exists. Amazon SQS returns this error only if the request includes attributes whose values differ from those of the existing queue. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. Errors API Version 2012-11-05 33 Amazon Simple Queue Service HTTP Status Code: 400 Examples API Reference The following example query requests create a new queue named MyQueue. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.CreateQueue X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueName":"MyQueue", "Attributes": { "VisibilityTimeout": "40" }, "tags": { "QueueType": "Production" } } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "QueueUrl":"https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue" Examples API Version 2012-11-05 34 Amazon Simple Queue Service API Reference } Example Using AWS query protocol Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=CreateQueue &QueueName=MyQueue &Attribute.1.Name=VisibilityTimeout &Attribute.1.Value=40 &Tag.Key=QueueType &Tag.Value=Production Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <CreateQueueResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <CreateQueueResult> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue</QueueUrl> </CreateQueueResult> <ResponseMetadata> <RequestId>9b20926c-8b35-5d8e-9559-ce1c22e754dc</RequestId> </ResponseMetadata> </CreateQueueResponse> Example The following example creates a delay queue which hides each message from consumers for the first 45 seconds that the message is in the queue by calling the CreateQueue action with the DelaySeconds attribute set to 45 seconds. Examples API Version 2012-11-05 35 Amazon Simple Queue Service API Reference Note Queue URLs and names are case-sensitive. Sample Request https://sqs.us-east-2.amazonaws.com/123456789012/MyQueue/ ?Action=CreateQueue &QueueName=MyQueue &Attribute.1.Name=DelaySeconds &Attribute.1.Value=45 &Expires=2020-12-20T22%3A52%3A43PST &Version=2012-11-05 &AUTHPARAMS See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 36 Amazon Simple Queue Service DeleteMessage API Reference Deletes the specified message from the specified queue. To select the message to delete, use the ReceiptHandle of the message (not the MessageId which you receive when you send the message). Amazon SQS can delete a message from a queue even if a visibility timeout setting causes the message to be locked by another consumer. Amazon SQS automatically deletes messages left in a queue longer than the retention period configured for the queue. Note Each time you receive a message, meaning when a consumer retrieves a message from the queue, it comes with a unique ReceiptHandle. If you receive the same message more than once, you will get a different ReceiptHandle each time. When you want to delete a message using the DeleteMessage action, you must use the ReceiptHandle from the most recent time you received the message. If you use an old ReceiptHandle, the request will succeed, but the message might not be deleted. For standard queues, it is possible to receive a message even after you delete it. This might happen on rare occasions if one of the servers which stores a copy of the message is unavailable when you send the request to delete the message. The copy remains on the server and might be returned to you during a subsequent receive request. You should ensure that your application is idempotent, so that receiving a message more than once does not cause issues. Request Syntax { "QueueUrl": "string", "ReceiptHandle": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format.
sqs-api-011
sqs-api.pdf
11
it. This might happen on rare occasions if one of the servers which stores a copy of the message is unavailable when you send the request to delete the message. The copy remains on the server and might be returned to you during a subsequent receive request. You should ensure that your application is idempotent, so that receiving a message more than once does not cause issues. Request Syntax { "QueueUrl": "string", "ReceiptHandle": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. DeleteMessage API Version 2012-11-05 37 Amazon Simple Queue Service QueueUrl API Reference The URL of the Amazon SQS queue from which messages are deleted. Queue URLs and names are case-sensitive. Type: String Required: Yes ReceiptHandle The receipt handle associated with the message to delete. Type: String Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidIdFormat This error has been deprecated. The specified receipt handle isn't valid for the current version. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. Response Elements API Version 2012-11-05 38 Amazon Simple Queue Service HTTP Status Code: 400 QueueDoesNotExist API Reference Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 ReceiptHandleIsInvalid The specified receipt handle isn't valid. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following example query request deletes a message from the queue named MyQueue. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Examples API Version 2012-11-05 39 Amazon Simple Queue Service API Reference X-Amz-Target: AmazonSQS.DeleteMessage X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "ReceiptHandle": "AQEB3LQoW7GQWgodQCEJXHjMvO/QkeCHiRldRfLC/E6RUggm +BjpthqxfoUOUn6Vs271qmrBaufFqEmnMKgk2n1EuUBne1pe+hZcrDE8IveUUPmqkUT54FGhAAjPX3oEIryz/ XeQ/muKAuLclcZvt2Q+ZDPW8DvZqMa1RoHxOqSq+6kQ4PwgQxB+VqDYvIc/LpHOoL4PTROBXgLPjWrzz/ knK6HTzKpqC4ESvFdJ/dkk2nvS0iqYOly5VQknK/lv/rTUOgEYevjJSrNLIPDgZGyvgcLwbm6+yo1cW/ c9cPDiVm96gIhVkuiCZ1gtskoOtyroZVPcY71clDG2EPZJeY8akMd3u+sXEMWhiOPFs1cgWQs2ugsL +vdwMCbsZRkXbJv7" } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: 0 Date: <Date> Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=DeleteMessage &ReceiptHandle=AQEBMeG2RcZZrIcgBkDFb6lHqL9B9tbbEHNh+4uxMIG +CPupPjqJtRswDlOr6hOTzgcq105i0iZNci5GS5RTnHTkD2zipM9gHfSP2tWPhY7HHsU5GCTZ +egzS5HiEvmGZ71g71Lucdk7mes1/ WGXnmU27K26Koo9GGrB0AKTv16dync1ezCMNyrBHEMUyIWS2lUTbrSj7fw93dgZSg2eWTk+thSVUB/ibOwpmj +wBN99nKQQklsZHtZd4exT1V3JHwP4kqz Examples API Version 2012-11-05 40 Amazon Simple Queue Service API Reference +D3C2RGn7js3nNdFpH41lBH8rCTZDU8DQp9eQNHLIL6RUf1WrI8gv8L7NErGlIH4Y3wZbFEOMKilVHenfpP2G6ElMuxyM3y +qdlZq4m00VGIIZeMg9PPmVsLtB7u9mruLyNFraN5ihKMjzQoKgA== Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <DeleteMessageResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>b5293cb5-d306-4a17-9048-b263635abe42</RequestId> </ResponseMetadata> </DeleteMessageResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 41 Amazon Simple Queue Service API Reference DeleteMessageBatch Deletes up to ten messages from the specified queue. This is a batch version of DeleteMessage. The result of the action on each message is reported individually in the response. Important Because the batch request can result in a combination of successful and unsuccessful actions, you should check for batch errors even when the call returns an HTTP status code of 200. Request Syntax { "Entries": [ { "Id": "string", "ReceiptHandle": "string" } ], "QueueUrl": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. Entries Lists the receipt handles for the messages to be deleted. Type: Array of DeleteMessageBatchRequestEntry objects Required: Yes QueueUrl The URL of the Amazon SQS queue from which messages are deleted. DeleteMessageBatch API Version 2012-11-05 42 Amazon Simple Queue Service API Reference Queue URLs and names are case-sensitive. Type: String Required: Yes Response Syntax { "Failed": [ { "Code": "string", "Id": "string", "Message": "string", "SenderFault": boolean } ], "Successful": [ { "Id": "string" } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Failed A list of BatchResultErrorEntry items. Type: Array of BatchResultErrorEntry objects Successful
sqs-api-012
sqs-api.pdf
12
DeleteMessageBatchRequestEntry objects Required: Yes QueueUrl The URL of the Amazon SQS queue from which messages are deleted. DeleteMessageBatch API Version 2012-11-05 42 Amazon Simple Queue Service API Reference Queue URLs and names are case-sensitive. Type: String Required: Yes Response Syntax { "Failed": [ { "Code": "string", "Id": "string", "Message": "string", "SenderFault": boolean } ], "Successful": [ { "Id": "string" } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Failed A list of BatchResultErrorEntry items. Type: Array of BatchResultErrorEntry objects Successful A list of DeleteMessageBatchResultEntry items. Type: Array of DeleteMessageBatchResultEntry objects Response Syntax API Version 2012-11-05 43 Amazon Simple Queue Service Errors API Reference For information about the errors that are common to all actions, see Common Errors. BatchEntryIdsNotDistinct Two or more batch entries in the request have the same Id. HTTP Status Code: 400 EmptyBatchRequest The batch request doesn't contain any entries. HTTP Status Code: 400 InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidBatchEntryId The Id of a batch entry in a batch request doesn't abide by the specification. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 Errors API Version 2012-11-05 44 Amazon Simple Queue Service TooManyEntriesInBatchRequest API Reference The batch request contains more entries than permissible. For Amazon SQS, the maximum number of entries you can include in a single SendMessageBatch, DeleteMessageBatch, or ChangeMessageVisibilityBatch request is 10. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following examples show how a DeleteMessageBatch request deletes two messages. You must URL-encode the entire URL. However, in this example only the message body is URL-encoded to make the example easier to read. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.DeleteMessageBatch X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Entries": [ { "Id": "msg1", "ReceiptHandle": "AQEBaZ+j5qUoOAoxlmrCQPkBm9njMWXqemmIG6shMHCO6fV20JrQYg/ AiZ8JELwLwOu5U61W+aIX5Qzu7GGofxJuvzymr4Ph53RiR0mudj4InLSgpSspYeTRDteBye5tV/txbZDdNZxsi Examples API Version 2012-11-05 45 Amazon Simple Queue Service API Reference +qqZA9xPnmMscKQqF6pGhnGIKrnkYGl45Nl6GPIZv62LrIRb6mSqOn1fn0yqrvmWuuY3w2UzQbaYunJWGxpzZze21EOBtywknU3Je/ g7G9is +c6K9hGniddzhLkK1tHzZKjejOU4jokaiB4nmi0dF3JqLzDsQuPF0Gi8qffhEvw56nl8QCbluSJScFhJYvoagGnDbwOnd9z50L239qtFIgETdpKyirlWwl/ NGjWJ45dqWpiW3d2Ws7q" }, { "Id": "msg2", "ReceiptHandle": "AQEB3LQoW7GQWgodQCEJXHjMvO/QkeCHiRldRfLC/E6RUggm +BjpthqxfoUOUn6Vs271qmrBaufFqEmnMKgk2n1EuUBne1pe+hZcrDE8IveUUPmqkUT54FGhAAjPX3oEIryz/ XeQ/muKAuLclcZvt2Q+ZDPW8DvZqMa1RoHxOqSq+6kQ4PwgQxB+VqDYvIc/LpHOoL4PTROBXgLPjWrzz/ knK6HTzKpqC4ESvFdJ/dkk2nvS0iqYOly5VQknK/lv/rTUOgEYevjJSrNLIPDgZGyvgcLwbm6+yo1cW/ c9cPDiVm96gIhVkuiCZ1gtskoOtyroZVPcY71clDG2EPZJeY8akMd3u+sXEMWhiOPFs1cgWQs2ugsL +vdwMCbsZRkXbJv7" } ] } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <> Date: <Date> Content-Type: application/x-amz-json-1.0 { "Failed": [], "Successful": [ { "Id": "msg2" }, { "Id": "msg1" } ] } Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Examples API Version 2012-11-05 46 Amazon Simple Queue Service API Reference Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=DeleteMessageBatch &DeleteMessageBatchRequestEntry.1.Id=msg1 &DeleteMessageBatchRequestEntry.1.ReceiptHandle=gfk0T0R0waama4fVFffkjPQrrvzMrOg0fTFk2LxT33EuB8wR0ZCFgKWyXGWFoqqpCIiprQUEhir %2F5LeGPpYTLzjqLQxyQYaQALeSNHb0us3uE84uujxpBhsDkZUQkjFFkNqBXn48xlMcVhTcI3YLH%2Bd %2BIqetIOHgBCZAPx6r%2B09dWaBXei6nbK5Ygih21DCDdAwFV68Jo8DXhb3ErEfoDqx7vyvC5nCpdwqv%2BJhU %2FTNGjNN8t51v5c%2FAXvQsAzyZVNapxUrHIt4NxRhKJ72uICcxruyE8eRXlxIVNgeNP8ZEDcw7zZU1Zw%3D %3D &DeleteMessageBatchRequestEntry.2.Id=msg2 &DeleteMessageBatchRequestEntry.2.ReceiptHandle=gfk0T0R0waama4fVFffkjKzmhMCymjQvfTFk2LxT33G4ms5subrE0deLKWSscPU1oD3J9zgeS4PQQ3U30qOumIE6AdAv3w %2F%2Fa1IXW6AqaWhGsEPaLm3Vf6IiWqdM8u5imB%2BNTwj3tQRzOWdTOePjOjPcTpRxBtXix %2BEvwJOZUma9wabv%2BSw6ZHjwmNcVDx8dZXJhVp16Bksiox %2FGrUvrVTCJRTWTLc59oHLLF8sEkKzRmGNzTDGTiV%2BYjHfQj60FD3rVaXmzTsoNxRhKJ72uIHVMGVQiAGgB %2BqAbSqfKHDQtVOmJJgkHug%3D%3D Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <DeleteMessageBatchResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <DeleteMessageBatchResult> <DeleteMessageBatchResultEntry> <Id>msg1</Id> </DeleteMessageBatchResultEntry> <DeleteMessageBatchResultEntry> <Id>msg2</Id> </DeleteMessageBatchResultEntry> </DeleteMessageBatchResult> <ResponseMetadata> <RequestId>d6f86b7a-74d1-4439-b43f-196a1e29cd85</RequestId> </ResponseMetadata> </DeleteMessageBatchResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: See Also API Version 2012-11-05 47 API Reference Amazon Simple Queue Service • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 48 Amazon Simple Queue Service DeleteQueue API Reference Deletes the queue specified by the QueueUrl, regardless of the queue's contents. Important Be careful with the DeleteQueue action: When you delete a queue, any messages in the queue are no longer available. When you delete a queue, the deletion process takes up to 60 seconds. Requests you send involving that queue during the 60 seconds might succeed. For example, a SendMessage request might succeed, but after 60 seconds the queue and the message you sent no longer exist. When you delete a queue, you must wait at least 60 seconds before creating a queue with the same name. Note Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. The delete operation uses the HTTP
sqs-api-013
sqs-api.pdf
13
available. When you delete a queue, the deletion process takes up to 60 seconds. Requests you send involving that queue during the 60 seconds might succeed. For example, a SendMessage request might succeed, but after 60 seconds the queue and the message you sent no longer exist. When you delete a queue, you must wait at least 60 seconds before creating a queue with the same name. Note Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. The delete operation uses the HTTP GET verb. Request Syntax { "QueueUrl": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. QueueUrl The URL of the Amazon SQS queue to delete. DeleteQueue API Version 2012-11-05 49 Amazon Simple Queue Service API Reference Queue URLs and names are case-sensitive. Type: String Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. Response Elements API Version 2012-11-05 50 Amazon Simple Queue Service HTTP Status Code: 400 Examples API Reference The following example query request deletes the specified queue. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.DeleteQueue X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl":"https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue" } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: 0 Date: <Date> Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Examples API Version 2012-11-05 51 Amazon Simple Queue Service API Reference Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=DeleteQueue Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <DeleteQueueResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>22b441f1-c3c3-54e4-9f57-1d817c509a21</RequestId> </ResponseMetadata> </DeleteQueueResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 52 Amazon Simple Queue Service API Reference GetQueueAttributes Gets attributes for the specified queue. Note To determine whether a queue is FIFO, you can check whether QueueName ends with the .fifo suffix. Request Syntax { "AttributeNames": [ "string" ], "QueueUrl": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. AttributeNames A list of attributes for which to retrieve information. The AttributeNames parameter is optional, but if you don't specify values for this parameter, the request returns empty results. Note In the future, new attributes might be added. If you write code that calls this action, we recommend that you structure your code so that it can handle new attributes gracefully. The following attributes are supported: GetQueueAttributes API Version 2012-11-05 53 Amazon Simple Queue Service API Reference Important The ApproximateNumberOfMessagesDelayed, ApproximateNumberOfMessagesNotVisible, and ApproximateNumberOfMessages metrics may not achieve consistency until at least 1 minute after the producers stop sending messages. This period is required for the queue metadata to reach eventual consistency. • All – Returns all values. • ApproximateNumberOfMessages – Returns the approximate number of messages available for retrieval from the queue. • ApproximateNumberOfMessagesDelayed – Returns the approximate number of messages in the queue that are delayed and not available for reading immediately. This can happen when the queue is configured as a delay queue or when a message has been sent with a delay parameter. • ApproximateNumberOfMessagesNotVisible – Returns the approximate number of messages that are in flight. Messages are considered to be in flight if they have been sent to
sqs-api-014
sqs-api.pdf
14
required for the queue metadata to reach eventual consistency. • All – Returns all values. • ApproximateNumberOfMessages – Returns the approximate number of messages available for retrieval from the queue. • ApproximateNumberOfMessagesDelayed – Returns the approximate number of messages in the queue that are delayed and not available for reading immediately. This can happen when the queue is configured as a delay queue or when a message has been sent with a delay parameter. • ApproximateNumberOfMessagesNotVisible – Returns the approximate number of messages that are in flight. Messages are considered to be in flight if they have been sent to a client but have not yet been deleted or have not yet reached the end of their visibility window. • CreatedTimestamp – Returns the time when the queue was created in seconds (epoch time). • DelaySeconds – Returns the default delay on the queue in seconds. • LastModifiedTimestamp – Returns the time when the queue was last changed in seconds (epoch time). • MaximumMessageSize – Returns the limit of how many bytes a message can contain before Amazon SQS rejects it. • MessageRetentionPeriod – Returns the length of time, in seconds, for which Amazon SQS retains a message. When you change a queue's attributes, the change can take up to 60 seconds for most of the attributes to propagate throughout the Amazon SQS system. Changes made to the MessageRetentionPeriod attribute can take up to 15 minutes and will impact existing messages in the queue potentially causing them to be expired and deleted if the MessageRetentionPeriod is reduced below the age of existing messages. • Policy – Returns the policy of the queue. Request Parameters API Version 2012-11-05 54 Amazon Simple Queue Service API Reference • QueueArn – Returns the Amazon resource name (ARN) of the queue. • ReceiveMessageWaitTimeSeconds – Returns the length of time, in seconds, for which the ReceiveMessage action waits for a message to arrive. • VisibilityTimeout – Returns the visibility timeout for the queue. For more information about the visibility timeout, see Visibility Timeout in the Amazon SQS Developer Guide. The following attributes apply only to dead-letter queues: • RedrivePolicy – The string that includes the parameters for the dead-letter queue functionality of the source queue as a JSON object. The parameters are as follows: • deadLetterTargetArn – The Amazon Resource Name (ARN) of the dead-letter queue to which Amazon SQS moves messages after the value of maxReceiveCount is exceeded. • maxReceiveCount – The number of times a message is delivered to the source queue before being moved to the dead-letter queue. Default: 10. When the ReceiveCount for a message exceeds the maxReceiveCount for a queue, Amazon SQS moves the message to the dead-letter-queue. • RedriveAllowPolicy – The string that includes the parameters for the permissions for the dead-letter queue redrive permission and which source queues can specify dead-letter queues as a JSON object. The parameters are as follows: • redrivePermission – The permission type that defines which source queues can specify the current queue as the dead-letter queue. Valid values are: • allowAll – (Default) Any source queues in this AWS account in the same Region can specify this queue as the dead-letter queue. • denyAll – No source queues can specify this queue as the dead-letter queue. • byQueue – Only queues specified by the sourceQueueArns parameter can specify this queue as the dead-letter queue. • sourceQueueArns – The Amazon Resource Names (ARN)s of the source queues that can specify this queue as the dead-letter queue and redrive messages. You can specify this parameter only when the redrivePermission parameter is set to byQueue. You can specify up to 10 source queue ARNs. To allow more than 10 source queues to specify dead- letter queues, set the redrivePermission parameter to allowAll. Request Parameters API Version 2012-11-05 55 Amazon Simple Queue Service API Reference Note The dead-letter queue of a FIFO queue must also be a FIFO queue. Similarly, the dead- letter queue of a standard queue must also be a standard queue. The following attributes apply only to server-side-encryption: • KmsMasterKeyId – Returns the ID of an AWS managed customer master key (CMK) for Amazon SQS or a custom CMK. For more information, see Key Terms. • KmsDataKeyReusePeriodSeconds – Returns the length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. For more information, see How Does the Data Key Reuse Period Work?. • SqsManagedSseEnabled – Returns information about whether the queue is using SSE- SQS encryption using SQS owned encryption keys. Only one server-side encryption option is supported per queue (for example, SSE-KMS or SSE-SQS). The following attributes apply only to FIFO (first-in-first-out) queues: • FifoQueue – Returns information about whether the queue is FIFO. For more information, see FIFO queue
sqs-api-015
sqs-api.pdf
15
• KmsDataKeyReusePeriodSeconds – Returns the length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. For more information, see How Does the Data Key Reuse Period Work?. • SqsManagedSseEnabled – Returns information about whether the queue is using SSE- SQS encryption using SQS owned encryption keys. Only one server-side encryption option is supported per queue (for example, SSE-KMS or SSE-SQS). The following attributes apply only to FIFO (first-in-first-out) queues: • FifoQueue – Returns information about whether the queue is FIFO. For more information, see FIFO queue logic in the Amazon SQS Developer Guide. Note To determine whether a queue is FIFO, you can check whether QueueName ends with the .fifo suffix. • ContentBasedDeduplication – Returns whether content-based deduplication is enabled for the queue. For more information, see Exactly-once processing in the Amazon SQS Developer Guide. The following attributes apply only to high throughput for FIFO queues: • DeduplicationScope – Specifies whether message deduplication occurs at the message group or queue level. Valid values are messageGroup and queue. • FifoThroughputLimit – Specifies whether the FIFO queue throughput quota applies to the entire queue or per message group. Valid values are perQueue and perMessageGroupId. The perMessageGroupId value is allowed only when the value for DeduplicationScope is messageGroup. Request Parameters API Version 2012-11-05 56 Amazon Simple Queue Service API Reference To enable high throughput for FIFO queues, do the following: • Set DeduplicationScope to messageGroup. • Set FifoThroughputLimit to perMessageGroupId. If you set these attributes to anything other than the values shown for enabling high throughput, normal throughput is in effect and deduplication occurs as specified. For information on throughput quotas, see Quotas related to messages in the Amazon SQS Developer Guide. Type: Array of strings Valid Values: All | Policy | VisibilityTimeout | MaximumMessageSize | MessageRetentionPeriod | ApproximateNumberOfMessages | ApproximateNumberOfMessagesNotVisible | CreatedTimestamp | LastModifiedTimestamp | QueueArn | ApproximateNumberOfMessagesDelayed | DelaySeconds | ReceiveMessageWaitTimeSeconds | RedrivePolicy | FifoQueue | ContentBasedDeduplication | KmsMasterKeyId | KmsDataKeyReusePeriodSeconds | DeduplicationScope | FifoThroughputLimit | RedriveAllowPolicy | SqsManagedSseEnabled Required: No QueueUrl The URL of the Amazon SQS queue whose attribute information is retrieved. Queue URLs and names are case-sensitive. Type: String Required: Yes Response Syntax { "Attributes": { "string" : "string" } } Response Syntax API Version 2012-11-05 57 Amazon Simple Queue Service Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Attributes A map of attributes to their respective values. Type: String to string map Valid Keys: All | Policy | VisibilityTimeout | MaximumMessageSize | MessageRetentionPeriod | ApproximateNumberOfMessages | ApproximateNumberOfMessagesNotVisible | CreatedTimestamp | LastModifiedTimestamp | QueueArn | ApproximateNumberOfMessagesDelayed | DelaySeconds | ReceiveMessageWaitTimeSeconds | RedrivePolicy | FifoQueue | ContentBasedDeduplication | KmsMasterKeyId | KmsDataKeyReusePeriodSeconds | DeduplicationScope | FifoThroughputLimit | RedriveAllowPolicy | SqsManagedSseEnabled Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidAttributeName The specified attribute doesn't exist. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 Response Elements API Version 2012-11-05 58 Amazon Simple Queue Service QueueDoesNotExist API Reference Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following example query request gets all the attribute values for the specified queue. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.GetQueueAtrributes X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { Examples API Version 2012-11-05 59 Amazon Simple Queue Service API Reference "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "AttributeNames": ["All"] } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "Attributes": { "QueueArn": "arn:aws:sqs:us-east-1:555555555555:MyQueue", "ApproximateNumberOfMessages": "0", "ApproximateNumberOfMessagesNotVisible": "0", "ApproximateNumberOfMessagesDelayed": "0", "CreatedTimestamp": "1676665337", "LastModifiedTimestamp": "1677096375", "VisibilityTimeout": "60", "MaximumMessageSize": "12345", "MessageRetentionPeriod": "345600", "DelaySeconds": "0", "Policy": "{\"Version\":\"2012-10-17\",\"Id\":\"Policy1677095510157\", \"Statement\":[{\"Sid\":\"Stmt1677095506939\",\"Effect\":\"Allow\",\"Principal \":\"*\",\"Action\":\"sqs:ReceiveMessage\",\"Resource\":\"arn:aws:sqs:us- east-1:555555555555:MyQueue6\"}]}", "RedriveAllowPolicy": "{\"redrivePermission\":\"allowAll\"}", "ReceiveMessageWaitTimeSeconds": "2", "SqsManagedSseEnabled": "true" } } Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Examples API Version 2012-11-05 60 Amazon Simple Queue Service API Reference Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=GetQueueAttributes &AttributeName.1=All Sample Response HTTP/1.1 200 OK
sqs-api-016
sqs-api.pdf
16
Amazon Simple Queue Service API Reference "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "AttributeNames": ["All"] } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "Attributes": { "QueueArn": "arn:aws:sqs:us-east-1:555555555555:MyQueue", "ApproximateNumberOfMessages": "0", "ApproximateNumberOfMessagesNotVisible": "0", "ApproximateNumberOfMessagesDelayed": "0", "CreatedTimestamp": "1676665337", "LastModifiedTimestamp": "1677096375", "VisibilityTimeout": "60", "MaximumMessageSize": "12345", "MessageRetentionPeriod": "345600", "DelaySeconds": "0", "Policy": "{\"Version\":\"2012-10-17\",\"Id\":\"Policy1677095510157\", \"Statement\":[{\"Sid\":\"Stmt1677095506939\",\"Effect\":\"Allow\",\"Principal \":\"*\",\"Action\":\"sqs:ReceiveMessage\",\"Resource\":\"arn:aws:sqs:us- east-1:555555555555:MyQueue6\"}]}", "RedriveAllowPolicy": "{\"redrivePermission\":\"allowAll\"}", "ReceiveMessageWaitTimeSeconds": "2", "SqsManagedSseEnabled": "true" } } Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Examples API Version 2012-11-05 60 Amazon Simple Queue Service API Reference Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=GetQueueAttributes &AttributeName.1=All Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <GetQueueAttributesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <GetQueueAttributesResult> <Attribute> <Name>QueueArn</Name> <Value>arn:aws:sqs:us-east-1:555555555555:MyQueue</Value> </Attribute> <Attribute> <Name>ApproximateNumberOfMessages</Name> <Value>5</Value> </Attribute> <Attribute> <Name>ApproximateNumberOfMessagesNotVisible</Name> <Value>0</Value> </Attribute> <Attribute> <Name>ApproximateNumberOfMessagesDelayed</Name> <Value>0</Value> </Attribute> <Attribute> <Name>CreatedTimestamp</Name> <Value>1677110910</Value> </Attribute> <Attribute> <Name>LastModifiedTimestamp</Name> <Value>1677110910</Value> </Attribute> <Attribute> <Name>VisibilityTimeout</Name> <Value>40</Value> </Attribute> <Attribute> <Name>MaximumMessageSize</Name> <Value>262144</Value> Examples API Version 2012-11-05 61 API Reference Amazon Simple Queue Service </Attribute> <Attribute> <Name>MessageRetentionPeriod</Name> <Value>345600</Value> </Attribute> <Attribute> <Name>DelaySeconds</Name> <Value>0</Value> </Attribute> <Attribute> <Name>ReceiveMessageWaitTimeSeconds</Name> <Value>0</Value> </Attribute> <Attribute> <Name>SqsManagedSseEnabled</Name> <Value>true</Value> </Attribute> </GetQueueAttributesResult> <ResponseMetadata> <RequestId>1cffc414-8cb4-54a8-9519-98644ca5f987</RequestId> </ResponseMetadata> </GetQueueAttributesResponse> Example The following example query request gets three attribute values for the specified queue. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.GetQueueAtrributes X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", Examples API Version 2012-11-05 62 Amazon Simple Queue Service API Reference "AttributeNames": ["VisibilityTimeout", "DelaySeconds", "ReceiveMessageWaitTimeSeconds"] } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "Attributes": { "VisibilityTimeout": "35", "DelaySeconds": "45", "ReceiveMessageWaitTimeSeconds": "20" } } Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=GetQueueAttributes &AttributeName.1=VisibilityTimeout &AttributeName.2=DelaySeconds &AttributeName.3=ReceiveMessageWaitTimeSeconds Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <GetQueueAttributesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> Examples API Version 2012-11-05 63 Amazon Simple Queue Service API Reference <GetQueueAttributesResult> <Attribute> <Name>VisibilityTimeout</Name> <Value>35</Value> </Attribute> <Attribute> <Name>DelaySeconds</Name> <Value>45</Value> </Attribute> <Attribute> <Name>ReceiveMessageWaitTimeSeconds</Name> <Value>20</Value> </Attribute> </GetQueueAttributesResult> <ResponseMetadata> <RequestId>60462930-c7fd-5ef8-b6a0-75a20b5e17b8</RequestId> </ResponseMetadata> </GetQueueAttributesResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 64 Amazon Simple Queue Service GetQueueUrl API Reference The GetQueueUrl API returns the URL of an existing Amazon SQS queue. This is useful when you know the queue's name but need to retrieve its URL for further operations. To access a queue owned by another AWS account, use the QueueOwnerAWSAccountId parameter to specify the account ID of the queue's owner. Note that the queue owner must grant you the necessary permissions to access the queue. For more information about accessing shared queues, see the AddPermission API or Allow developers to write messages to a shared queue in the Amazon SQS Developer Guide. Request Syntax { "QueueName": "string", "QueueOwnerAWSAccountId": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. QueueName (Required) The name of the queue for which you want to fetch the URL. The name can be up to 80 characters long and can include alphanumeric characters, hyphens (-), and underscores (_). Queue URLs and names are case-sensitive. Type: String Required: Yes QueueOwnerAWSAccountId (Optional) The AWS account ID of the account that created the queue. This is only required when you are attempting to access a queue owned by another AWS account. Type: String Required: No GetQueueUrl API Version 2012-11-05 65 Amazon Simple Queue Service Response Syntax { "QueueUrl": "string" } Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. QueueUrl The URL of the queue. Type: String Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. Response Syntax API Version 2012-11-05 66 Amazon Simple Queue Service API Reference • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages.
sqs-api-017
sqs-api.pdf
17
InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. Response Syntax API Version 2012-11-05 66 Amazon Simple Queue Service API Reference • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following are examples of using the GetQueueUrl API via both JSON and query protocols. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.GetQueueUrl X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueName": "MyQueue" } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Examples API Version 2012-11-05 67 Amazon Simple Queue Service Date: <Date> Content-Type: application/x-amz-json-1.0 { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue" API Reference } Example Using AWS query protocol Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=GetQueueUrl &QueueName=MyQueue Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <GetQueueUrlResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <GetQueueUrlResult> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue</QueueUrl> </GetQueueUrlResult> <ResponseMetadata> <RequestId>552d6f30-4c8e-5b32-aaed-33408c7d6c38</RequestId> </ResponseMetadata> </GetQueueUrlResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface See Also API Version 2012-11-05 68 API Reference Amazon Simple Queue Service • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 69 Amazon Simple Queue Service API Reference ListDeadLetterSourceQueues Returns a list of your queues that have the RedrivePolicy queue attribute configured with a dead-letter queue. The ListDeadLetterSourceQueues methods supports pagination. Set parameter MaxResults in the request to specify the maximum number of results to be returned in the response. If you do not set MaxResults, the response includes a maximum of 1,000 results. If you set MaxResults and there are additional results to display, the response includes a value for NextToken. Use NextToken as a parameter in your next request to ListDeadLetterSourceQueues to receive the next page of results. For more information about using dead-letter queues, see Using Amazon SQS Dead-Letter Queues in the Amazon SQS Developer Guide. Request Syntax { "MaxResults": number, "NextToken": "string", "QueueUrl": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. MaxResults Maximum number of results to include in the response. Value range is 1 to 1000. You must set MaxResults to receive a value for NextToken in the response. Type: Integer Required: No NextToken Pagination token to request the next set of results. ListDeadLetterSourceQueues API Version 2012-11-05 70 API Reference Amazon Simple Queue Service Type: String Required: No QueueUrl The URL of a dead-letter queue. Queue URLs and names are case-sensitive. Type: String Required: Yes Response Syntax { "NextToken": "string", "queueUrls": [ "string" ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. NextToken Pagination token to include in the next request. Token value is null if there are no additional results to request, or if you did not set MaxResults in the request. Type: String queueUrls A list of source queue URLs that have the RedrivePolicy queue attribute configured with a dead-letter queue. Type: Array of strings Response Syntax API Version 2012-11-05 71 Amazon Simple Queue Service Errors API Reference For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas
sqs-api-018
sqs-api.pdf
18
all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following example query request returns a list of dead letter source queues. In this example, only one source queue, MySourceQueue, is configured with a dead-letter queue. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Errors API Version 2012-11-05 72 API Reference Amazon Simple Queue Service Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.ListDeadLetterSourceQueues X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue" } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "queueUrls": [ "https://sqs.us-east-1.amazonaws.com/123456789012/MySourceQueue</QueueUrl>" ] } Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Authorization: <AuthParams> Examples API Version 2012-11-05 73 Amazon Simple Queue Service API Reference Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=ListDeadLetterSourceQueues Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <ListDeadLetterSourceQueuesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ListDeadLetterSourceQueuesResult/> <ResponseMetadata> <RequestId>8e70ce7e-e3d4-5109-9204-920e21745daf</RequestId> </ResponseMetadata> </ListDeadLetterSourceQueuesResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 74 Amazon Simple Queue Service API Reference ListMessageMoveTasks Gets the most recent message movement tasks (up to 10) under a specific source queue. Note • This action is currently limited to supporting message redrive from dead-letter queues (DLQs) only. In this context, the source queue is the dead-letter queue (DLQ), while the destination queue can be the original source queue (from which the messages were driven to the dead-letter-queue), or a custom destination queue. • Only one active message movement task is supported per queue at any given time. Request Syntax { "MaxResults": number, "SourceArn": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. MaxResults The maximum number of results to include in the response. The default is 1, which provides the most recent message movement task. The upper limit is 10. Type: Integer Required: No SourceArn The ARN of the queue whose message movement tasks are to be listed. Type: String ListMessageMoveTasks API Version 2012-11-05 75 API Reference Amazon Simple Queue Service Required: Yes Response Syntax { "Results": [ { "ApproximateNumberOfMessagesMoved": number, "ApproximateNumberOfMessagesToMove": number, "DestinationArn": "string", "FailureReason": "string", "MaxNumberOfMessagesPerSecond": number, "SourceArn": "string", "StartedTimestamp": number, "Status": "string", "TaskHandle": "string" } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Results A list of message movement tasks and their attributes. Type: Array of ListMessageMoveTasksResultEntry objects Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 Response Syntax API Version 2012-11-05 76 Amazon Simple Queue Service InvalidSecurity API Reference The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 ResourceNotFoundException One or more specified resources don't exist. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples Example Using AWS query protocol The following example query lists the five most recent message movement tasks on MyDeadLetterQueue, which has only two tasks since it was created. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests
sqs-api-019
sqs-api.pdf
19
is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 ResourceNotFoundException One or more specified resources don't exist. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples Example Using AWS query protocol The following example query lists the five most recent message movement tasks on MyDeadLetterQueue, which has only two tasks since it was created. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Examples API Version 2012-11-05 77 Amazon Simple Queue Service X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=ListMessageMoveTasks &SourceArn=arn:aws:sqs:us-east-1:555555555555:MyDeadLetterQueue API Reference &MaxResults=5 Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <ListMessageMoveTasksResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ListMessageMoveTasksResult> <Result> <ApproximateNumberOfMessagesMoved>50</ApproximateNumberOfMessagesMoved> <ApproximateNumberOfMessagesToMove>0</ApproximateNumberOfMessagesToMove> <DestinationArn>arn:aws:sqs:us-east-1:555555555555:MySourceQueue</ DestinationArn> <MaxNumberOfMessagesPerSecond>20</MaxNumberOfMessagesPerSecond> <SourceArn>arn:aws:sqs:us-east-1:555555555555:MyDeadLetterQueue</SourceArn> <StartedTimestamp>1684429053010</StartedTimestamp> <Status>COMPLETED</Status> </Result> <Result> <ApproximateNumberOfMessagesMoved>50</ApproximateNumberOfMessagesMoved> <ApproximateNumberOfMessagesToMove>100</ApproximateNumberOfMessagesToMove> <DestinationArn>arn:aws:sqs:us-east-1:555555555555:MySourceQueue</ DestinationArn> <MaxNumberOfMessagesPerSecond>10</MaxNumberOfMessagesPerSecond> <SourceArn>arn:aws:sqs:us-east-1:555555555555:MyDeadLetterQueue</SourceArn> <StartedTimestamp>1684429993999</StartedTimestamp> <Status>RUNNING</Status> <TaskHandle>eyJ0YXNrSWQiOiJkYzE2OWUwNC0wZTU1LTQ0ZDItYWE5MC1jMDgwY2ExZjM2ZjciLCJzb3VyY2VBcm4iOiJhcm46YXdzOnNxczp1cy1lYXN0LTE6MTc3NzE1MjU3NDM2Ok15RGVhZExldHRlclF1ZXVlIn0=</ TaskHandle> </Result> <ResponseMetadata> <RequestId>9b20926c-8b35-5d8e-9559-ce1c22e754dc</RequestId> </ResponseMetadata> </ListMessageMoveTasksResult> </ListMessageMoveTasksResponse> Examples API Version 2012-11-05 78 Amazon Simple Queue Service See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 79 Amazon Simple Queue Service ListQueues API Reference Returns a list of your queues in the current region. The response includes a maximum of 1,000 results. If you specify a value for the optional QueueNamePrefix parameter, only queues with a name that begins with the specified value are returned. The listQueues methods supports pagination. Set parameter MaxResults in the request to specify the maximum number of results to be returned in the response. If you do not set MaxResults, the response includes a maximum of 1,000 results. If you set MaxResults and there are additional results to display, the response includes a value for NextToken. Use NextToken as a parameter in your next request to listQueues to receive the next page of results. Note Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. Request Syntax { "MaxResults": number, "NextToken": "string", "QueueNamePrefix": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. MaxResults Maximum number of results to include in the response. Value range is 1 to 1000. You must set MaxResults to receive a value for NextToken in the response. Type: Integer Required: No ListQueues API Version 2012-11-05 80 Amazon Simple Queue Service NextToken Pagination token to request the next set of results. API Reference Type: String Required: No QueueNamePrefix A string to use for filtering the list results. Only those queues whose name begins with the specified string are returned. Queue URLs and names are case-sensitive. Type: String Required: No Response Syntax { "NextToken": "string", "QueueUrls": [ "string" ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. NextToken Pagination token to include in the next request. Token value is null if there are no additional results to request, or if you did not set MaxResults in the request. Type: String QueueUrls A list of queue URLs, up to 1,000 entries, or the value of MaxResults that you sent in the request. Response Syntax API Version 2012-11-05 81 Amazon Simple Queue Service Type: Array of strings Errors API Reference For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following example query request returns the queues whose names begin with the letter t The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example
sqs-api-020
sqs-api.pdf
20
permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following example query request returns the queues whose names begin with the letter t The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Errors API Version 2012-11-05 82 API Reference Amazon Simple Queue Service Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.ListQueues X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueNamePrefix": "My" } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "QueueUrls": [ "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue", "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue1648169377027", "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue1648169549830", "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue1648227401019", "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue1648248132466", "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue1649201932174", "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue2" ] } Example Using AWS query protocol Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded Examples API Version 2012-11-05 83 API Reference Amazon Simple Queue Service X-Amz-Date: <Date> Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=ListQueues&QueueNamePrefix=M Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <ListQueuesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ListQueuesResult> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/ MyQueue1648169377027</QueueUrl> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/ MyQueue1648169549830</QueueUrl> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/ MyQueue1648227401019</QueueUrl> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/ MyQueue1648248132466</QueueUrl> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/ MyQueue1649201932174</QueueUrl> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue22</QueueUrl> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue23</QueueUrl> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue233</ QueueUrl> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue5</QueueUrl> <QueueUrl>https://sqs.us-east-1.amazonaws.com/177715257436/MyQueueTest</ QueueUrl> </ListQueuesResult> <ResponseMetadata> <RequestId>f525e5e2-86cd-5d1b-aee9-b992443254c0</RequestId> </ResponseMetadata> </ListQueuesResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET See Also API Version 2012-11-05 84 API Reference Amazon Simple Queue Service • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 85 Amazon Simple Queue Service ListQueueTags API Reference List all cost allocation tags added to the specified Amazon SQS queue. For an overview, see Tagging Your Amazon SQS Queues in the Amazon SQS Developer Guide. Note Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. Request Syntax { "QueueUrl": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. QueueUrl The URL of the queue. Type: String Required: Yes Response Syntax { "Tags": { "string" : "string" } } ListQueueTags API Version 2012-11-05 86 Amazon Simple Queue Service Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Tags The list of all tags added to the specified queue. Type: String to string map Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 Response Elements API Version 2012-11-05 87 API Reference Amazon Simple Queue Service UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples This example illustrates one usage of ListQueueTags. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.ListQueueTags X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/" } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "Tags": { "QueueType": "Production" } } Examples API Version 2012-11-05 88 API Reference Amazon Simple Queue Service Example Using AWS query protocol Sample Request POST /177715257436/MyQueue HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=ListQueueTags Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <ListQueueTagsResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ListQueueTagsResult> <Tag> <Key>QueueType</Key> <Value>Production</Value> </Tag> </ListQueueTagsResult> <ResponseMetadata> <RequestId>02c89a6b-9fc0-564a-9ed1-c61b5cacdc6d</RequestId> </ResponseMetadata> </ListQueueTagsResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 See Also API Version 2012-11-05 89 Amazon Simple Queue Service • AWS SDK for Java V2 • AWS SDK for JavaScript
sqs-api-021
sqs-api.pdf
21
query protocol Sample Request POST /177715257436/MyQueue HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=ListQueueTags Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <ListQueueTagsResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ListQueueTagsResult> <Tag> <Key>QueueType</Key> <Value>Production</Value> </Tag> </ListQueueTagsResult> <ResponseMetadata> <RequestId>02c89a6b-9fc0-564a-9ed1-c61b5cacdc6d</RequestId> </ResponseMetadata> </ListQueueTagsResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 See Also API Version 2012-11-05 89 Amazon Simple Queue Service • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2012-11-05 90 Amazon Simple Queue Service PurgeQueue API Reference Deletes available messages in a queue (including in-flight messages) specified by the QueueURL parameter. Important When you use the PurgeQueue action, you can't retrieve any messages deleted from a queue. The message deletion process takes up to 60 seconds. We recommend waiting for 60 seconds regardless of your queue's size. Messages sent to the queue before you call PurgeQueue might be received but are deleted within the next minute. Messages sent to the queue after you call PurgeQueue might be deleted while the queue is being purged. Request Syntax { "QueueUrl": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. QueueUrl The URL of the queue from which the PurgeQueue action deletes messages. Queue URLs and names are case-sensitive. Type: String Required: Yes PurgeQueue API Version 2012-11-05 91 Amazon Simple Queue Service Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 PurgeQueueInProgress Indicates that the specified queue previously received a PurgeQueue request within the last 60 seconds (the time it can take to delete the messages in the queue). HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. Response Elements API Version 2012-11-05 92 Amazon Simple Queue Service HTTP Status Code: 400 Examples API Reference The following example query request purges a queue named MyQueue. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.PurgeQueue X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/" } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: 0 Date: <Date> Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue HTTP/1.1 Examples API Version 2012-11-05 93 Amazon Simple Queue Service API Reference Host: sqs.us-east-1.amazonaws.com Content-Type: application/x-www-form-urlencoded X-Amz-Date: <Date> Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=PurgeQueue Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <PurgeQueueResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>706cb8e1-8799-5ef8-9472-e4914393f2f0</RequestId> </ResponseMetadata> </PurgeQueueResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 94 Amazon Simple Queue Service ReceiveMessage API Reference Retrieves one or more messages (up to 10), from the specified queue. Using the WaitTimeSeconds parameter enables long-poll support. For more information, see Amazon SQS Long Polling in the Amazon SQS Developer Guide. Short poll is the default behavior where a weighted random set of machines is sampled on a ReceiveMessage call. Therefore, only the messages on the sampled machines are returned. If the number of messages in the queue is small (fewer than 1,000), you most likely get fewer messages than you requested per ReceiveMessage call. If the number of messages in the queue is extremely small, you might not
sqs-api-022
sqs-api.pdf
22
one or more messages (up to 10), from the specified queue. Using the WaitTimeSeconds parameter enables long-poll support. For more information, see Amazon SQS Long Polling in the Amazon SQS Developer Guide. Short poll is the default behavior where a weighted random set of machines is sampled on a ReceiveMessage call. Therefore, only the messages on the sampled machines are returned. If the number of messages in the queue is small (fewer than 1,000), you most likely get fewer messages than you requested per ReceiveMessage call. If the number of messages in the queue is extremely small, you might not receive any messages in a particular ReceiveMessage response. If this happens, repeat the request. For each message returned, the response includes the following: • The message body. • An MD5 digest of the message body. For information about MD5, see RFC1321. • The MessageId you received when you sent the message to the queue. • The receipt handle. • The message attributes. • An MD5 digest of the message attributes. The receipt handle is the identifier you must provide when deleting the message. For more information, see Queue and Message Identifiers in the Amazon SQS Developer Guide. You can provide the VisibilityTimeout parameter in your request. The parameter is applied to the messages that Amazon SQS returns in the response. If you don't include the parameter, the overall visibility timeout for the queue is used for the returned messages. The default visibility timeout for a queue is 30 seconds. Note In the future, new attributes might be added. If you write code that calls this action, we recommend that you structure your code so that it can handle new attributes gracefully. ReceiveMessage API Version 2012-11-05 95 API Reference Amazon Simple Queue Service Request Syntax { "AttributeNames": [ "string" ], "MaxNumberOfMessages": number, "MessageAttributeNames": [ "string" ], "MessageSystemAttributeNames": [ "string" ], "QueueUrl": "string", "ReceiveRequestAttemptId": "string", "VisibilityTimeout": number, "WaitTimeSeconds": number } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. AttributeNames This parameter has been deprecated. Important This parameter has been discontinued but will be supported for backward compatibility. To provide attribute names, you are encouraged to use MessageSystemAttributeNames. A list of attributes that need to be returned along with each message. These attributes include: • All – Returns all values. • ApproximateFirstReceiveTimestamp – Returns the time the message was first received from the queue (epoch time in milliseconds). • ApproximateReceiveCount – Returns the number of times a message has been received across all queues but not deleted. • AWSTraceHeader – Returns the AWS X-Ray trace header string. • SenderId Request Syntax API Version 2012-11-05 96 Amazon Simple Queue Service API Reference • For a user, returns the user ID, for example ABCDEFGHI1JKLMNOPQ23R. • For an IAM role, returns the IAM role ID, for example ABCDE1F2GH3I4JK5LMNOP:i- a123b456. • SentTimestamp – Returns the time the message was sent to the queue (epoch time in milliseconds). • SqsManagedSseEnabled – Enables server-side queue encryption using SQS owned encryption keys. Only one server-side encryption option is supported per queue (for example, SSE-KMS or SSE-SQS). • MessageDeduplicationId – Returns the value provided by the producer that calls the SendMessage action. • MessageGroupId – Returns the value provided by the producer that calls the SendMessage action. Messages with the same MessageGroupId are returned in sequence. • SequenceNumber – Returns the value provided by Amazon SQS. Type: Array of strings Valid Values: All | Policy | VisibilityTimeout | MaximumMessageSize | MessageRetentionPeriod | ApproximateNumberOfMessages | ApproximateNumberOfMessagesNotVisible | CreatedTimestamp | LastModifiedTimestamp | QueueArn | ApproximateNumberOfMessagesDelayed | DelaySeconds | ReceiveMessageWaitTimeSeconds | RedrivePolicy | FifoQueue | ContentBasedDeduplication | KmsMasterKeyId | KmsDataKeyReusePeriodSeconds | DeduplicationScope | FifoThroughputLimit | RedriveAllowPolicy | SqsManagedSseEnabled Required: No MaxNumberOfMessages The maximum number of messages to return. Amazon SQS never returns more messages than this value (however, fewer messages might be returned). Valid values: 1 to 10. Default: 1. Type: Integer Required: No MessageAttributeNames The name of the message attribute, where N is the index. Request Parameters API Version 2012-11-05 97 Amazon Simple Queue Service API Reference • The name can contain alphanumeric characters and the underscore (_), hyphen (-), and period (.). • The name is case-sensitive and must be unique among all attribute names for the message. • The name must not start with AWS-reserved prefixes such as AWS. or Amazon. (or any casing variants). • The name must not start or end with a period (.), and it should not have periods in succession (..). • The name can be up to 256 characters long. When using ReceiveMessage, you can send a list of attribute names to receive, or you can return all of the attributes by specifying All or .* in your request. You can also use all message attributes starting with
sqs-api-023
sqs-api.pdf
23
is case-sensitive and must be unique among all attribute names for the message. • The name must not start with AWS-reserved prefixes such as AWS. or Amazon. (or any casing variants). • The name must not start or end with a period (.), and it should not have periods in succession (..). • The name can be up to 256 characters long. When using ReceiveMessage, you can send a list of attribute names to receive, or you can return all of the attributes by specifying All or .* in your request. You can also use all message attributes starting with a prefix, for example bar.*. Type: Array of strings Required: No MessageSystemAttributeNames A list of attributes that need to be returned along with each message. These attributes include: • All – Returns all values. • ApproximateFirstReceiveTimestamp – Returns the time the message was first received from the queue (epoch time in milliseconds). • ApproximateReceiveCount – Returns the number of times a message has been received across all queues but not deleted. • AWSTraceHeader – Returns the AWS X-Ray trace header string. • SenderId • For a user, returns the user ID, for example ABCDEFGHI1JKLMNOPQ23R. • For an IAM role, returns the IAM role ID, for example ABCDE1F2GH3I4JK5LMNOP:i- a123b456. • SentTimestamp – Returns the time the message was sent to the queue (epoch time in milliseconds). • SqsManagedSseEnabled – Enables server-side queue encryption using SQS owned encryption keys. Only one server-side encryption option is supported per queue (for example, SSE-KMS or SSE-SQS). Request Parameters API Version 2012-11-05 98 Amazon Simple Queue Service API Reference • MessageDeduplicationId – Returns the value provided by the producer that calls the SendMessage action. • MessageGroupId – Returns the value provided by the producer that calls the SendMessage action. Messages with the same MessageGroupId are returned in sequence. • SequenceNumber – Returns the value provided by Amazon SQS. Type: Array of strings Valid Values: All | SenderId | SentTimestamp | ApproximateReceiveCount | ApproximateFirstReceiveTimestamp | SequenceNumber | MessageDeduplicationId | MessageGroupId | AWSTraceHeader | DeadLetterQueueSourceArn Required: No QueueUrl The URL of the Amazon SQS queue from which messages are received. Queue URLs and names are case-sensitive. Type: String Required: Yes ReceiveRequestAttemptId This parameter applies only to FIFO (first-in-first-out) queues. The token used for deduplication of ReceiveMessage calls. If a networking issue occurs after a ReceiveMessage action, and instead of a response you receive a generic error, it is possible to retry the same action with an identical ReceiveRequestAttemptId to retrieve the same set of messages, even if their visibility timeout has not yet expired. • You can use ReceiveRequestAttemptId only for 5 minutes after a ReceiveMessage action. • When you set FifoQueue, a caller of the ReceiveMessage action can provide a ReceiveRequestAttemptId explicitly. • It is possible to retry the ReceiveMessage action with the same ReceiveRequestAttemptId if none of the messages have been modified (deleted or had their visibility changes). Request Parameters API Version 2012-11-05 99 Amazon Simple Queue Service API Reference • During a visibility timeout, subsequent calls with the same ReceiveRequestAttemptId return the same messages and receipt handles. If a retry occurs within the deduplication interval, it resets the visibility timeout. For more information, see Visibility Timeout in the Amazon SQS Developer Guide. Important If a caller of the ReceiveMessage action still processes messages when the visibility timeout expires and messages become visible, another worker consuming from the same queue can receive the same messages and therefore process duplicates. Also, if a consumer whose message processing time is longer than the visibility timeout tries to delete the processed messages, the action fails with an error. To mitigate this effect, ensure that your application observes a safe threshold before the visibility timeout expires and extend the visibility timeout as necessary. • While messages with a particular MessageGroupId are invisible, no more messages belonging to the same MessageGroupId are returned until the visibility timeout expires. You can still receive messages with another MessageGroupId as long as it is also visible. • If a caller of ReceiveMessage can't track the ReceiveRequestAttemptId, no retries work until the original visibility timeout expires. As a result, delays might occur but the messages in the queue remain in a strict order. The maximum length of ReceiveRequestAttemptId is 128 characters. ReceiveRequestAttemptId can contain alphanumeric characters (a-z, A-Z, 0-9) and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~). For best practices of using ReceiveRequestAttemptId, see Using the ReceiveRequestAttemptId Request Parameter in the Amazon SQS Developer Guide. Type: String Required: No VisibilityTimeout The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved by a ReceiveMessage request. If not specified, the default visibility timeout for the queue is used, which is 30 seconds. Understanding VisibilityTimeout: Request Parameters API Version 2012-11-05 100 Amazon Simple Queue Service API Reference • When a message is received from a queue,
sqs-api-024
sqs-api.pdf
24
length of ReceiveRequestAttemptId is 128 characters. ReceiveRequestAttemptId can contain alphanumeric characters (a-z, A-Z, 0-9) and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~). For best practices of using ReceiveRequestAttemptId, see Using the ReceiveRequestAttemptId Request Parameter in the Amazon SQS Developer Guide. Type: String Required: No VisibilityTimeout The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved by a ReceiveMessage request. If not specified, the default visibility timeout for the queue is used, which is 30 seconds. Understanding VisibilityTimeout: Request Parameters API Version 2012-11-05 100 Amazon Simple Queue Service API Reference • When a message is received from a queue, it becomes temporarily invisible to other consumers for the duration of the visibility timeout. This prevents multiple consumers from processing the same message simultaneously. If the message is not deleted or its visibility timeout is not extended before the timeout expires, it becomes visible again and can be retrieved by other consumers. • Setting an appropriate visibility timeout is crucial. If it's too short, the message might become visible again before processing is complete, leading to duplicate processing. If it's too long, it delays the reprocessing of messages if the initial processing fails. • You can adjust the visibility timeout using the --visibility-timeout parameter in the receive-message command to match the processing time required by your application. • A message that isn't deleted or a message whose visibility isn't extended before the visibility timeout expires counts as a failed receive. Depending on the configuration of the queue, the message might be sent to the dead-letter queue. For more information, see Visibility Timeout in the Amazon SQS Developer Guide. Type: Integer Required: No WaitTimeSeconds The duration (in seconds) for which the call waits for a message to arrive in the queue before returning. If a message is available, the call returns sooner than WaitTimeSeconds. If no messages are available and the wait time expires, the call does not return a message list. If you are using the Java SDK, it returns a ReceiveMessageResponse object, which has a empty list instead of a Null object. Important To avoid HTTP errors, ensure that the HTTP response timeout for ReceiveMessage requests is longer than the WaitTimeSeconds parameter. For example, with the Java SDK, you can set HTTP transport settings using the NettyNioAsyncHttpClient for asynchronous clients, or the ApacheHttpClient for synchronous clients. Type: Integer Required: No Request Parameters API Version 2012-11-05 101 API Reference Amazon Simple Queue Service Response Syntax { "Messages": [ { "Attributes": { "string" : "string" }, "Body": "string", "MD5OfBody": "string", "MD5OfMessageAttributes": "string", "MessageAttributes": { "string" : { "BinaryListValues": [ blob ], "BinaryValue": blob, "DataType": "string", "StringListValues": [ "string" ], "StringValue": "string" } }, "MessageId": "string", "ReceiptHandle": "string" } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Messages A list of messages. Type: Array of Message objects Errors For information about the errors that are common to all actions, see Common Errors. Response Syntax API Version 2012-11-05 102 API Reference Amazon Simple Queue Service InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 KmsAccessDenied The caller doesn't have the required KMS access. HTTP Status Code: 400 KmsDisabled The request was denied due to request throttling. HTTP Status Code: 400 KmsInvalidKeyUsage The request was rejected for one of the following reasons: • The KeyUsage value of the KMS key is incompatible with the API operation. • The encryption algorithm or signing algorithm specified for the operation is incompatible with the type of key material in the KMS key (KeySpec). HTTP Status Code: 400 KmsInvalidState The request was rejected because the state of the specified resource is not valid for this request. HTTP Status Code: 400 KmsNotFound The request was rejected because the specified entity or resource could not be found. HTTP Status Code: 400 KmsOptInRequired The request was rejected because the specified key policy isn't syntactically or semantically correct. Errors API Version 2012-11-05 103 Amazon Simple Queue Service HTTP Status Code: 400 KmsThrottled AWS KMS throttles requests for the following conditions. HTTP Status Code: 400 OverLimit API Reference The specified action violates a limit. For example, ReceiveMessage returns this error if the maximum number of in flight messages is reached and AddPermission returns this error if the maximum number of permissions for the queue is reached. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the
sqs-api-025
sqs-api.pdf
25
Code: 400 OverLimit API Reference The specified action violates a limit. For example, ReceiveMessage returns this error if the maximum number of in flight messages is reached and AddPermission returns this error if the maximum number of permissions for the queue is reached. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following example query request receives messages from the specified queue. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Examples API Version 2012-11-05 104 API Reference Amazon Simple Queue Service Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.ReceiveMessage X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "MaxNumberOfMessages": 5, "VisibilityTimeout": 15, "AttributeNames": ["All"] } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "Messages": [ { "Attributes": { "SenderId": "AIDASSYFHUBOBT7F4XT75", "ApproximateFirstReceiveTimestamp": "1677112433437", "ApproximateReceiveCount": "1", "SentTimestamp": "1677112427387" }, "Body": "This is a test message", "MD5OfBody": "fafb00f5732ab283681e124bf8747ed1", "MessageId": "219f8380-5770-4cc2-8c3e-5c715e145f5e", "ReceiptHandle": "AQEBaZ+j5qUoOAoxlmrCQPkBm9njMWXqemmIG6shMHCO6fV20JrQYg/ AiZ8JELwLwOu5U61W+aIX5Qzu7GGofxJuvzymr4Ph53RiR0mudj4InLSgpSspYeTRDteBye5tV/txbZDdNZxsi +qqZA9xPnmMscKQqF6pGhnGIKrnkYGl45Nl6GPIZv62LrIRb6mSqOn1fn0yqrvmWuuY3w2UzQbaYunJWGxpzZze21EOBtywknU3Je/ Examples API Version 2012-11-05 105 Amazon Simple Queue Service g7G9is API Reference +c6K9hGniddzhLkK1tHzZKjejOU4jokaiB4nmi0dF3JqLzDsQuPF0Gi8qffhEvw56nl8QCbluSJScFhJYvoagGnDbwOnd9z50L239qtFIgETdpKyirlWwl/ NGjWJ45dqWpiW3d2Ws7q" } ] } Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=ReceiveMessage &MaxNumberOfMessages=5 &VisibilityTimeout=15 &AttributeName=All Sample Response HTTP/1.1 200 OK <ReceiveMessageResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ReceiveMessageResult> <Message> <MessageId>60e827c3-c8a5-410a-af0e-fb43746e70b1</MessageId> <ReceiptHandle>AQEBwPTK2fT2gy97H1iyU5in9umgT+Y4IOxyKGOzpZa8iemEqoR5/ aPn0xAodmiVTzyrW7S4e8XwcWbB04XK92jIQzUpiGwRFA4Dl7r3GOw84Qzq/0OBQe/ JaKxJw6iilafYA5fo1SJQo5Wg8xXbJHTVlJqgvTXd/ UtlByLMhWMi0JMra1UUjYiPsGtYUpLVnOaRkYSPvzRnFFYUbcqCW9lm2Bi/ jQKK6KNOZyCCfIh8TooE5i4P2L9N3o9yUHwMdv6p0nb5lKaGurQ2sJwwsyhXf38ZHnVN6pWwsqQnWKYuEXpxPofxd2lcLdgUurMpydS22DzCrkAaf6gmrdxbmCAoeQxE0sFf8alwX9yQmcOjny9aLGe7ro4Vl5o5KMr5hHM4vHEyhwi4wHeKM6MGX0vATA==</ ReceiptHandle> <MD5OfBody>0e024d309850c78cba5eabbeff7cae71</MD5OfBody> <Body>test message body 1</Body> <Attribute> <Name>SenderId</Name> <Value>AIDASSYFHUBOBT7F4XT75</Value> Examples API Version 2012-11-05 106 API Reference Amazon Simple Queue Service </Attribute> <Attribute> <Name>ApproximateFirstReceiveTimestamp</Name> <Value>1677112300463</Value> </Attribute> <Attribute> <Name>ApproximateReceiveCount</Name> <Value>1</Value> </Attribute> <Attribute> <Name>SentTimestamp</Name> <Value>1677111805489</Value> </Attribute> </Message> </ReceiveMessageResult> <ResponseMetadata> <RequestId>5ba605cc-1e4b-58ba-93db-59bca8677ec9</RequestId> </ResponseMetadata> </ReceiveMessageResponse> Example The following example enables long polling by calling the ReceiveMessage action with the WaitTimeSeconds parameter set to 10 seconds. Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.ReceiveMessage X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "WaitTimeSeconds": 10, "MaxNumberOfMessages": 5, "VisibilityTimeout": 15, "AttributeNames": ["All"] Examples API Version 2012-11-05 107 Amazon Simple Queue Service } Example API Reference The following example shows the request and response when using the parameter MessageSystemAttributeNames. Sample Request aws sqs receive-message \ --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/MyQueue \ --message-system-attribute-names SentTimestamp SenderId Sample Response { "Messages": [ { "MessageId": "abc1234d-5678-90ab-cdef-EXAMPLE11111", "ReceiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...", "MD5OfBody": "e99a18c428cb38d5f260853678922e03", "Body": "Example message", "Attributes": { "SenderId": "AIDAEXAMPLE123ABC", "SentTimestamp": "1638368280000" } } ] } Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Examples API Version 2012-11-05 108 Amazon Simple Queue Service API Reference Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=ReceiveMessage &WaitTimeSeconds=10 &MaxNumberOfMessages=5 &VisibilityTimeout=15 &AttributeName=All See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 109 Amazon Simple Queue Service RemovePermission API Reference Revokes any permissions in the queue policy that matches the specified Label parameter. Note • Only the owner of a queue can remove permissions from it. • Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. • To remove the ability to change queue permissions, you must deny permission to the AddPermission, RemovePermission, and SetQueueAttributes actions in your IAM policy. Request Syntax { "Label": "string", "QueueUrl": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. Label The identification of the permission to remove. This is the label added using the AddPermission action. Type: String Required: Yes QueueUrl The URL of the Amazon SQS queue from which permissions are removed. Queue URLs and names are case-sensitive. RemovePermission API Version 2012-11-05 110 Amazon Simple Queue Service API Reference Type: String Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common
sqs-api-026
sqs-api.pdf
26
Common Parameters. The request accepts the following data in JSON format. Label The identification of the permission to remove. This is the label added using the AddPermission action. Type: String Required: Yes QueueUrl The URL of the Amazon SQS queue from which permissions are removed. Queue URLs and names are case-sensitive. RemovePermission API Version 2012-11-05 110 Amazon Simple Queue Service API Reference Type: String Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Response Elements API Version 2012-11-05 111 Amazon Simple Queue Service Examples API Reference The following example query request removes the MyLabel permission from the queue named MyQueue. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.RemovePermission X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Label": "MyLabel" } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: 0 Date: <Date> Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Examples API Version 2012-11-05 112 API Reference Amazon Simple Queue Service X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=RemovePermission&Label=MyLabel Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <RemovePermissionResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>133cc8b8-21a1-5aba-b65a-94c8e50d917f</RequestId> </ResponseMetadata> </RemovePermissionResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 113 Amazon Simple Queue Service SendMessage Delivers a message to the specified queue. Important API Reference A message can include only XML, JSON, and unformatted text. The following Unicode characters are allowed. For more information, see the W3C specification for characters. #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF Amazon SQS does not throw an exception or completely reject the message if it contains invalid characters. Instead, it replaces those invalid characters with U+FFFD before storing the message in the queue, as long as the message body contains at least one valid character. Request Syntax { "DelaySeconds": number, "MessageAttributes": { "string" : { "BinaryListValues": [ blob ], "BinaryValue": blob, "DataType": "string", "StringListValues": [ "string" ], "StringValue": "string" } }, "MessageBody": "string", "MessageDeduplicationId": "string", "MessageGroupId": "string", "MessageSystemAttributes": { "string" : { "BinaryListValues": [ blob ], "BinaryValue": blob, "DataType": "string", "StringListValues": [ "string" ], "StringValue": "string" } }, "QueueUrl": "string" SendMessage API Version 2012-11-05 114 Amazon Simple Queue Service } Request Parameters API Reference For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. DelaySeconds The length of time, in seconds, for which to delay a specific message. Valid values: 0 to 900. Maximum: 15 minutes. Messages with a positive DelaySeconds value become available for processing after the delay period is finished. If you don't specify a value, the default value for the queue applies. Note When you set FifoQueue, you can't set DelaySeconds per message. You can set this parameter only on a queue level. Type: Integer Required: No MessageAttributes Each message attribute consists of a Name, Type, and Value. For more information, see Amazon SQS message attributes in the Amazon SQS Developer Guide. Type: String to MessageAttributeValue object map Required: No MessageBody The message to send. The minimum size is one character. The maximum size is 256 KiB. Important A message can include only XML, JSON, and unformatted text. The following Unicode characters are allowed. For more information, see the W3C specification for characters. Request Parameters API Version 2012-11-05 115 Amazon Simple Queue Service API Reference #x9
sqs-api-027
sqs-api.pdf
27
this parameter only on a queue level. Type: Integer Required: No MessageAttributes Each message attribute consists of a Name, Type, and Value. For more information, see Amazon SQS message attributes in the Amazon SQS Developer Guide. Type: String to MessageAttributeValue object map Required: No MessageBody The message to send. The minimum size is one character. The maximum size is 256 KiB. Important A message can include only XML, JSON, and unformatted text. The following Unicode characters are allowed. For more information, see the W3C specification for characters. Request Parameters API Version 2012-11-05 115 Amazon Simple Queue Service API Reference #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF Amazon SQS does not throw an exception or completely reject the message if it contains invalid characters. Instead, it replaces those invalid characters with U+FFFD before storing the message in the queue, as long as the message body contains at least one valid character. Type: String Required: Yes MessageDeduplicationId This parameter applies only to FIFO (first-in-first-out) queues. The token used for deduplication of sent messages. If a message with a particular MessageDeduplicationId is sent successfully, any messages sent with the same MessageDeduplicationId are accepted successfully but aren't delivered during the 5-minute deduplication interval. For more information, see Exactly-once processing in the Amazon SQS Developer Guide. • Every message must have a unique MessageDeduplicationId, • You may provide a MessageDeduplicationId explicitly. • If you aren't able to provide a MessageDeduplicationId and you enable ContentBasedDeduplication for your queue, Amazon SQS uses a SHA-256 hash to generate the MessageDeduplicationId using the body of the message (but not the attributes of the message). • If you don't provide a MessageDeduplicationId and the queue doesn't have ContentBasedDeduplication set, the action fails with an error. • If the queue has ContentBasedDeduplication set, your MessageDeduplicationId overrides the generated one. • When ContentBasedDeduplication is in effect, messages with identical content sent within the deduplication interval are treated as duplicates and only one copy of the message is delivered. • If you send one message with ContentBasedDeduplication enabled and then another message with a MessageDeduplicationId that is the same as the one generated for the first MessageDeduplicationId, the two messages are treated as duplicates and only one copy of the message is delivered. Request Parameters API Version 2012-11-05 116 Amazon Simple Queue Service API Reference Note The MessageDeduplicationId is available to the consumer of the message (this can be useful for troubleshooting delivery issues). If a message is sent successfully but the acknowledgement is lost and the message is resent with the same MessageDeduplicationId after the deduplication interval, Amazon SQS can't detect duplicate messages. Amazon SQS continues to keep track of the message deduplication ID even after the message is received and deleted. The maximum length of MessageDeduplicationId is 128 characters. MessageDeduplicationId can contain alphanumeric characters (a-z, A-Z, 0-9) and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~). For best practices of using MessageDeduplicationId, see Using the MessageDeduplicationId Property in the Amazon SQS Developer Guide. Type: String Required: No MessageGroupId This parameter applies only to FIFO (first-in-first-out) queues. The tag that specifies that a message belongs to a specific message group. Messages that belong to the same message group are processed in a FIFO manner (however, messages in different message groups might be processed out of order). To interleave multiple ordered streams within a single queue, use MessageGroupId values (for example, session data for multiple users). In this scenario, multiple consumers can process the queue, but the session data of each user is processed in a FIFO fashion. • You must associate a non-empty MessageGroupId with a message. If you don't provide a MessageGroupId, the action fails. • ReceiveMessage might return messages with multiple MessageGroupId values. For each MessageGroupId, the messages are sorted by time sent. The caller can't specify a MessageGroupId. The maximum length of MessageGroupId is 128 characters. Valid values: alphanumeric characters and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~). Request Parameters API Version 2012-11-05 117 Amazon Simple Queue Service API Reference For best practices of using MessageGroupId, see Using the MessageGroupId Property in the Amazon SQS Developer Guide. Important MessageGroupId is required for FIFO queues. You can't use it for Standard queues. Type: String Required: No MessageSystemAttributes The message system attribute to send. Each message system attribute consists of a Name, Type, and Value. Important • Currently, the only supported message system attribute is AWSTraceHeader. Its type must be String and its value must be a correctly formatted AWS X-Ray trace header string. • The size of a message system attribute doesn't count towards the total size of a message. Type: String to MessageSystemAttributeValue object map Valid Keys: AWSTraceHeader Required: No QueueUrl The URL of the Amazon SQS queue to which a message is sent. Queue URLs and names are case-sensitive. Type: String Required: Yes Request Parameters API Version 2012-11-05 118
sqs-api-028
sqs-api.pdf
28
to send. Each message system attribute consists of a Name, Type, and Value. Important • Currently, the only supported message system attribute is AWSTraceHeader. Its type must be String and its value must be a correctly formatted AWS X-Ray trace header string. • The size of a message system attribute doesn't count towards the total size of a message. Type: String to MessageSystemAttributeValue object map Valid Keys: AWSTraceHeader Required: No QueueUrl The URL of the Amazon SQS queue to which a message is sent. Queue URLs and names are case-sensitive. Type: String Required: Yes Request Parameters API Version 2012-11-05 118 API Reference Amazon Simple Queue Service Response Syntax { "MD5OfMessageAttributes": "string", "MD5OfMessageBody": "string", "MD5OfMessageSystemAttributes": "string", "MessageId": "string", "SequenceNumber": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. MD5OfMessageAttributes An MD5 digest of the non-URL-encoded message attribute string. You can use this attribute to verify that Amazon SQS received the message correctly. Amazon SQS URL-decodes the message before creating the MD5 digest. For information about MD5, see RFC1321. Type: String MD5OfMessageBody An MD5 digest of the non-URL-encoded message body string. You can use this attribute to verify that Amazon SQS received the message correctly. Amazon SQS URL-decodes the message before creating the MD5 digest. For information about MD5, see RFC1321. Type: String MD5OfMessageSystemAttributes An MD5 digest of the non-URL-encoded message system attribute string. You can use this attribute to verify that Amazon SQS received the message correctly. Amazon SQS URL-decodes the message before creating the MD5 digest. Type: String MessageId An attribute containing the MessageId of the message sent to the queue. For more information, see Queue and Message Identifiers in the Amazon SQS Developer Guide. Response Syntax API Version 2012-11-05 119 Amazon Simple Queue Service Type: String SequenceNumber API Reference This parameter applies only to FIFO (first-in-first-out) queues. The large, non-consecutive number that Amazon SQS assigns to each message. The length of SequenceNumber is 128 bits. SequenceNumber continues to increase for a particular MessageGroupId. Type: String Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidMessageContents The message contains characters outside the allowed set. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 KmsAccessDenied The caller doesn't have the required KMS access. HTTP Status Code: 400 KmsDisabled The request was denied due to request throttling. Errors API Version 2012-11-05 120 Amazon Simple Queue Service HTTP Status Code: 400 KmsInvalidKeyUsage API Reference The request was rejected for one of the following reasons: • The KeyUsage value of the KMS key is incompatible with the API operation. • The encryption algorithm or signing algorithm specified for the operation is incompatible with the type of key material in the KMS key (KeySpec). HTTP Status Code: 400 KmsInvalidState The request was rejected because the state of the specified resource is not valid for this request. HTTP Status Code: 400 KmsNotFound The request was rejected because the specified entity or resource could not be found. HTTP Status Code: 400 KmsOptInRequired The request was rejected because the specified key policy isn't syntactically or semantically correct. HTTP Status Code: 400 KmsThrottled AWS KMS throttles requests for the following conditions. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. Errors API Version 2012-11-05 121 Amazon Simple Queue Service API Reference • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following example SendMessage request sends a message containing This is a test message to the queue. You must URL-encode the entire URL. However, in this example only the message body is URL-encoded to make the example easier to read. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SendMessage X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "MessageBody": "This is a test message", "MessageAttributes": { "my_attribute_name_1": { "DataType": "String", "StringValue": "my_attribute_value_1" Examples API Version 2012-11-05 122 Amazon Simple Queue Service }, "my_attribute_name_2": { "DataType": "String", "StringValue": "my_attribute_value_2" API Reference } } } Sample Response HTTP/1.1 200 OK x-amzn-RequestId:
sqs-api-029
sqs-api.pdf
29
easier to read. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SendMessage X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "MessageBody": "This is a test message", "MessageAttributes": { "my_attribute_name_1": { "DataType": "String", "StringValue": "my_attribute_value_1" Examples API Version 2012-11-05 122 Amazon Simple Queue Service }, "my_attribute_name_2": { "DataType": "String", "StringValue": "my_attribute_value_2" API Reference } } } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "MD5OfMessageAttributes": "c48838208d2b4e14e3ca0093a8443f09", "MD5OfMessageBody": "fafb00f5732ab283681e124bf8747ed1", "MessageId": "219f8380-5770-4cc2-8c3e-5c715e145f5e" } Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=SendMessage &MessageBody=This+is+a+test+message &MessageAttribute.1.Name=my_attribute_name_1 &MessageAttribute.1.Value.StringValue=my_attribute_value_1 &MessageAttribute.1.Value.DataType=String &MessageAttribute.2.Name=my_attribute_name_2 &MessageAttribute.2.Value.StringValue=my_attribute_value_2 &MessageAttribute.2.Value.DataType=String Examples API Version 2012-11-05 123 Amazon Simple Queue Service Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> API Reference <SendMessageResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <SendMessageResult> <MessageId>374cec7b-d0c8-4a2e-ad0b-67be763cf97e</MessageId> <MD5OfMessageBody>fafb00f5732ab283681e124bf8747ed1</MD5OfMessageBody> <MD5OfMessageAttributes>c48838208d2b4e14e3ca0093a8443f09</ MD5OfMessageAttributes> </SendMessageResult> <ResponseMetadata> <RequestId>7fe4446e-b452-53f7-8f85-181e06f2dd99</RequestId> </ResponseMetadata> </SendMessageResponse> Example The following example creates a message timer—applying a 45-second initial visibility delay to a single message— by calling the SendMessage action with the DelaySeconds parameter set to 45 seconds. Note Queue URLs and names are case-sensitive. Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SendMessage X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "MessageBody": "This is a test message", Examples API Version 2012-11-05 124 API Reference Amazon Simple Queue Service "DelaySeconds": 45 } Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=SendMessage &MessageBody=This+is+a+test+message &DelaySeconds=45 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 125 Amazon Simple Queue Service SendMessageBatch API Reference You can use SendMessageBatch to send up to 10 messages to the specified queue by assigning either identical or different values to each message (or by not assigning values at all). This is a batch version of SendMessage. For a FIFO queue, multiple messages within a single batch are enqueued in the order they are sent. The result of sending each message is reported individually in the response. Because the batch request can result in a combination of successful and unsuccessful actions, you should check for batch errors even when the call returns an HTTP status code of 200. The maximum allowed individual message size and the maximum total payload size (the sum of the individual lengths of all of the batched messages) are both 256 KiB (262,144 bytes). Important A message can include only XML, JSON, and unformatted text. The following Unicode characters are allowed. For more information, see the W3C specification for characters. #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF Amazon SQS does not throw an exception or completely reject the message if it contains invalid characters. Instead, it replaces those invalid characters with U+FFFD before storing the message in the queue, as long as the message body contains at least one valid character. If you don't specify the DelaySeconds parameter for an entry, Amazon SQS uses the default value for the queue. Request Syntax { "Entries": [ { "DelaySeconds": number, "Id": "string", "MessageAttributes": { "string" : { "BinaryListValues": [ blob ], "BinaryValue": blob, SendMessageBatch API Version 2012-11-05 126 Amazon Simple Queue Service API Reference "DataType": "string", "StringListValues": [ "string" ], "StringValue": "string" } }, "MessageBody": "string", "MessageDeduplicationId": "string", "MessageGroupId": "string", "MessageSystemAttributes": { "string" : { "BinaryListValues": [ blob ], "BinaryValue": blob, "DataType": "string", "StringListValues": [ "string" ], "StringValue": "string" } } } ], "QueueUrl": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. Entries A list of SendMessageBatchRequestEntry items. Type: Array of SendMessageBatchRequestEntry objects Required: Yes QueueUrl The URL of the Amazon SQS queue to which batched messages are sent. Queue URLs and names are case-sensitive. Type: String Request Parameters API Version 2012-11-05 127 API Reference Amazon Simple Queue Service Required: Yes Response Syntax { "Failed": [ { "Code": "string", "Id": "string", "Message": "string", "SenderFault": boolean } ], "Successful": [ { "Id": "string", "MD5OfMessageAttributes": "string", "MD5OfMessageBody": "string", "MD5OfMessageSystemAttributes": "string", "MessageId": "string", "SequenceNumber": "string" } ] } Response Elements If the action is successful, the service sends back an
sqs-api-030
sqs-api.pdf
30
following data in JSON format. Entries A list of SendMessageBatchRequestEntry items. Type: Array of SendMessageBatchRequestEntry objects Required: Yes QueueUrl The URL of the Amazon SQS queue to which batched messages are sent. Queue URLs and names are case-sensitive. Type: String Request Parameters API Version 2012-11-05 127 API Reference Amazon Simple Queue Service Required: Yes Response Syntax { "Failed": [ { "Code": "string", "Id": "string", "Message": "string", "SenderFault": boolean } ], "Successful": [ { "Id": "string", "MD5OfMessageAttributes": "string", "MD5OfMessageBody": "string", "MD5OfMessageSystemAttributes": "string", "MessageId": "string", "SequenceNumber": "string" } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Failed A list of BatchResultErrorEntry items with error details about each message that can't be enqueued. Type: Array of BatchResultErrorEntry objects Successful A list of SendMessageBatchResultEntry items. Type: Array of SendMessageBatchResultEntry objects Response Syntax API Version 2012-11-05 128 Amazon Simple Queue Service Errors API Reference For information about the errors that are common to all actions, see Common Errors. BatchEntryIdsNotDistinct Two or more batch entries in the request have the same Id. HTTP Status Code: 400 BatchRequestTooLong The length of all the messages put together is more than the limit. HTTP Status Code: 400 EmptyBatchRequest The batch request doesn't contain any entries. HTTP Status Code: 400 InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidBatchEntryId The Id of a batch entry in a batch request doesn't abide by the specification. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 KmsAccessDenied The caller doesn't have the required KMS access. HTTP Status Code: 400 KmsDisabled The request was denied due to request throttling. Errors API Version 2012-11-05 129 Amazon Simple Queue Service HTTP Status Code: 400 KmsInvalidKeyUsage API Reference The request was rejected for one of the following reasons: • The KeyUsage value of the KMS key is incompatible with the API operation. • The encryption algorithm or signing algorithm specified for the operation is incompatible with the type of key material in the KMS key (KeySpec). HTTP Status Code: 400 KmsInvalidState The request was rejected because the state of the specified resource is not valid for this request. HTTP Status Code: 400 KmsNotFound The request was rejected because the specified entity or resource could not be found. HTTP Status Code: 400 KmsOptInRequired The request was rejected because the specified key policy isn't syntactically or semantically correct. HTTP Status Code: 400 KmsThrottled AWS KMS throttles requests for the following conditions. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. Errors API Version 2012-11-05 130 Amazon Simple Queue Service API Reference • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 TooManyEntriesInBatchRequest The batch request contains more entries than permissible. For Amazon SQS, the maximum number of entries you can include in a single SendMessageBatch, DeleteMessageBatch, or ChangeMessageVisibilityBatch request is 10. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following example SendMessageBatch request sends two messages to the queue. You must URL-encode the entire URL. However, in this example only the message body is URL-encoded to make the example easier to read. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SendMessageBatch X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { Examples API Version 2012-11-05 131 Amazon Simple Queue Service API Reference "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Entries": [ { "Id": "test_msg_001", "MessageBody": "test message body 1" }, { "Id": "test_msg_002", "MessageBody": "test message body 2", "DelaySeconds": 60, "MessageAttributes": { "my_attribute_name_1": { "DataType": "String", "StringValue": "my_attribute_value_1" } } } ] } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "Failed": [], "Successful": [ { "Id": "test_msg_001", "MD5OfMessageBody": "0e024d309850c78cba5eabbeff7cae71", "MessageId": "f4eb349f-cd33-4bc4-bdc2-e557c900d41d" }, { "Id": "test_msg_002", "MD5OfMessageAttributes": "8ef4d60dbc8efda9f260e1dfd09d29f3", "MD5OfMessageBody": "27118326006d3829667a400ad23d5d98", "MessageId": "1dcfcd50-5a67-45ae-ae4c-1c152b5effb9" } ] } Examples API Version 2012-11-05 132 API Reference Amazon Simple Queue Service Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=SendMessageBatch &SendMessageBatchRequestEntry.1.Id=test_msg_001 &SendMessageBatchRequestEntry.1.MessageBody=test%20message%20body%201 &SendMessageBatchRequestEntry.2.Id=test_msg_002 &SendMessageBatchRequestEntry.2.MessageBody=test%20message%20body%202 &SendMessageBatchRequestEntry.2.DelaySeconds=60 &SendMessageBatchRequestEntry.2.MessageAttribute.1.Name=test_attribute_name_1 &SendMessageBatchRequestEntry.2.MessageAttribute.1.Value.StringValue=test_attribute_value_1 &SendMessageBatchRequestEntry.2.MessageAttribute.1.Value.DataType=String Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <SendMessageBatchResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <SendMessageBatchResult> <SendMessageBatchResultEntry> <Id>test_msg_001</Id> <MessageId>60e827c3-c8a5-410a-af0e-fb43746e70b1</MessageId> <MD5OfMessageBody>0e024d309850c78cba5eabbeff7cae71</MD5OfMessageBody> </SendMessageBatchResultEntry> <SendMessageBatchResultEntry> <Id>test_msg_00</Id> <MessageId>c6e7fc6a-b802-4724-be06-59833004578b</MessageId> <MD5OfMessageBody>7fb8146a82f95e0af155278f406862c2</MD5OfMessageBody> <MD5OfMessageAttributes>ba056227cfd9533dba1f72ad9816d233</ MD5OfMessageAttributes>
sqs-api-031
sqs-api.pdf
31
Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "Failed": [], "Successful": [ { "Id": "test_msg_001", "MD5OfMessageBody": "0e024d309850c78cba5eabbeff7cae71", "MessageId": "f4eb349f-cd33-4bc4-bdc2-e557c900d41d" }, { "Id": "test_msg_002", "MD5OfMessageAttributes": "8ef4d60dbc8efda9f260e1dfd09d29f3", "MD5OfMessageBody": "27118326006d3829667a400ad23d5d98", "MessageId": "1dcfcd50-5a67-45ae-ae4c-1c152b5effb9" } ] } Examples API Version 2012-11-05 132 API Reference Amazon Simple Queue Service Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=SendMessageBatch &SendMessageBatchRequestEntry.1.Id=test_msg_001 &SendMessageBatchRequestEntry.1.MessageBody=test%20message%20body%201 &SendMessageBatchRequestEntry.2.Id=test_msg_002 &SendMessageBatchRequestEntry.2.MessageBody=test%20message%20body%202 &SendMessageBatchRequestEntry.2.DelaySeconds=60 &SendMessageBatchRequestEntry.2.MessageAttribute.1.Name=test_attribute_name_1 &SendMessageBatchRequestEntry.2.MessageAttribute.1.Value.StringValue=test_attribute_value_1 &SendMessageBatchRequestEntry.2.MessageAttribute.1.Value.DataType=String Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <SendMessageBatchResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <SendMessageBatchResult> <SendMessageBatchResultEntry> <Id>test_msg_001</Id> <MessageId>60e827c3-c8a5-410a-af0e-fb43746e70b1</MessageId> <MD5OfMessageBody>0e024d309850c78cba5eabbeff7cae71</MD5OfMessageBody> </SendMessageBatchResultEntry> <SendMessageBatchResultEntry> <Id>test_msg_00</Id> <MessageId>c6e7fc6a-b802-4724-be06-59833004578b</MessageId> <MD5OfMessageBody>7fb8146a82f95e0af155278f406862c2</MD5OfMessageBody> <MD5OfMessageAttributes>ba056227cfd9533dba1f72ad9816d233</ MD5OfMessageAttributes> </SendMessageBatchResultEntry> </SendMessageBatchResult> <ResponseMetadata> Examples API Version 2012-11-05 133 Amazon Simple Queue Service API Reference <RequestId>5150a701-14f7-5609-b136-fb71a0ca744a</RequestId> </ResponseMetadata> </SendMessageBatchResponse> Example The following example sends multiple messages with message timers—applying a visibility delay of variable length to the messages in the batch—by calling the SendMessageBatch action without a value for DelaySeconds for the first message and with the values of 45 seconds and 2 minutes for the second and third messages. Note If you don't set a value for the DelaySeconds parameter, the message might still be subject to a delay if you add the message to a delay queue. For more information about using delay queues, see Amazon SQS Delay Queues in the Amazon SQS Developer Guide. Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SendMessageBatch X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Entries": [ { "Id": "test_msg_no_message_timer", "MessageBody": "test message body 1" }, { "Id": "test_msg_delay_45_seconds", "MessageBody": "test message body 2", "DelaySeconds": 45 Examples API Version 2012-11-05 134 Amazon Simple Queue Service }, { "Id": "test_msg_delay_2_minutes", "MessageBody": "test message body 3", "DelaySeconds": 120 API Reference } ] } Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=SendMessageBatch &SendMessageBatchRequestEntry.1.Id=test_msg_no_message_timer &SendMessageBatchRequestEntry.1.MessageBody=test%20message%20body%201 &SendMessageBatchRequestEntry.2.Id=test_msg_delay_45_seconds &SendMessageBatchRequestEntry.2.MessageBody=test%20message%20body%202 &SendMessageBatchRequestEntry.2.DelaySeconds=45 &SendMessageBatchRequestEntry.3.Id=test_msg_delay_2_minutes &SendMessageBatchRequestEntry.3.MessageBody=test%20message%20body%203 &SendMessageBatchRequestEntry.3.DelaySeconds=120 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 See Also API Version 2012-11-05 135 Amazon Simple Queue Service • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2012-11-05 136 Amazon Simple Queue Service SetQueueAttributes API Reference Sets the value of one or more queue attributes, like a policy. When you change a queue's attributes, the change can take up to 60 seconds for most of the attributes to propagate throughout the Amazon SQS system. Changes made to the MessageRetentionPeriod attribute can take up to 15 minutes and will impact existing messages in the queue potentially causing them to be expired and deleted if the MessageRetentionPeriod is reduced below the age of existing messages. Note • In the future, new attributes might be added. If you write code that calls this action, we recommend that you structure your code so that it can handle new attributes gracefully. • Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. • To remove the ability to change queue permissions, you must deny permission to the AddPermission, RemovePermission, and SetQueueAttributes actions in your IAM policy. Request Syntax { "Attributes": { "string" : "string" }, "QueueUrl": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. Attributes A map of attributes to set. SetQueueAttributes API Version 2012-11-05 137 Amazon Simple Queue Service API Reference The following lists the names, descriptions, and values of the special request parameters that the SetQueueAttributes action uses: • DelaySeconds – The length of time, in seconds, for which the delivery of all messages in the queue is delayed. Valid values: An integer from 0 to 900 (15 minutes). Default: 0. • MaximumMessageSize – The limit of how many bytes a message can contain before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes (1 KiB) up to 262,144 bytes (256 KiB). Default: 262,144 (256 KiB). • MessageRetentionPeriod – The length of time, in seconds, for which Amazon SQS retains a message. Valid values: An integer representing seconds, from 60 (1 minute) to 1,209,600 (14 days). Default: 345,600 (4 days). When you change a queue's attributes, the change can take up to 60 seconds for most of the attributes to propagate throughout the Amazon SQS system. Changes made to the MessageRetentionPeriod attribute can take up to 15 minutes and will impact existing messages in
sqs-api-032
sqs-api.pdf
32
SQS rejects it. Valid values: An integer from 1,024 bytes (1 KiB) up to 262,144 bytes (256 KiB). Default: 262,144 (256 KiB). • MessageRetentionPeriod – The length of time, in seconds, for which Amazon SQS retains a message. Valid values: An integer representing seconds, from 60 (1 minute) to 1,209,600 (14 days). Default: 345,600 (4 days). When you change a queue's attributes, the change can take up to 60 seconds for most of the attributes to propagate throughout the Amazon SQS system. Changes made to the MessageRetentionPeriod attribute can take up to 15 minutes and will impact existing messages in the queue potentially causing them to be expired and deleted if the MessageRetentionPeriod is reduced below the age of existing messages. • Policy – The queue's policy. A valid AWS policy. For more information about policy structure, see Overview of AWS IAM Policies in the AWS Identity and Access Management User Guide. • ReceiveMessageWaitTimeSeconds – The length of time, in seconds, for which a ReceiveMessage action waits for a message to arrive. Valid values: An integer from 0 to 20 (seconds). Default: 0. • VisibilityTimeout – The visibility timeout for the queue, in seconds. Valid values: An integer from 0 to 43,200 (12 hours). Default: 30. For more information about the visibility timeout, see Visibility Timeout in the Amazon SQS Developer Guide. The following attributes apply only to dead-letter queues: • RedrivePolicy – The string that includes the parameters for the dead-letter queue functionality of the source queue as a JSON object. The parameters are as follows: • deadLetterTargetArn – The Amazon Resource Name (ARN) of the dead-letter queue to which Amazon SQS moves messages after the value of maxReceiveCount is exceeded. • maxReceiveCount – The number of times a message is delivered to the source queue before being moved to the dead-letter queue. Default: 10. When the ReceiveCount for a message exceeds the maxReceiveCount for a queue, Amazon SQS moves the message to the dead-letter-queue. Request Parameters API Version 2012-11-05 138 Amazon Simple Queue Service API Reference • RedriveAllowPolicy – The string that includes the parameters for the permissions for the dead-letter queue redrive permission and which source queues can specify dead-letter queues as a JSON object. The parameters are as follows: • redrivePermission – The permission type that defines which source queues can specify the current queue as the dead-letter queue. Valid values are: • allowAll – (Default) Any source queues in this AWS account in the same Region can specify this queue as the dead-letter queue. • denyAll – No source queues can specify this queue as the dead-letter queue. • byQueue – Only queues specified by the sourceQueueArns parameter can specify this queue as the dead-letter queue. • sourceQueueArns – The Amazon Resource Names (ARN)s of the source queues that can specify this queue as the dead-letter queue and redrive messages. You can specify this parameter only when the redrivePermission parameter is set to byQueue. You can specify up to 10 source queue ARNs. To allow more than 10 source queues to specify dead- letter queues, set the redrivePermission parameter to allowAll. Note The dead-letter queue of a FIFO queue must also be a FIFO queue. Similarly, the dead- letter queue of a standard queue must also be a standard queue. The following attributes apply only to server-side-encryption: • KmsMasterKeyId – The ID of an AWS managed customer master key (CMK) for Amazon SQS or a custom CMK. For more information, see Key Terms. While the alias of the AWS-managed CMK for Amazon SQS is always alias/aws/sqs, the alias of a custom CMK can, for example, be alias/MyAlias . For more examples, see KeyId in the AWS Key Management Service API Reference. • KmsDataKeyReusePeriodSeconds – The length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. An integer representing seconds, between 60 seconds (1 minute) and 86,400 seconds (24 hours). Default: 300 (5 minutes). A shorter time period provides better security but results in more calls to KMS which might incur charges after Free Tier. For more information, see How Does the Data Key Reuse Period Work?. Request Parameters API Version 2012-11-05 139 Amazon Simple Queue Service API Reference • SqsManagedSseEnabled – Enables server-side queue encryption using SQS owned encryption keys. Only one server-side encryption option is supported per queue (for example, SSE-KMS or SSE-SQS). The following attribute applies only to FIFO (first-in-first-out) queues: • ContentBasedDeduplication – Enables content-based deduplication. For more information, see Exactly-once processing in the Amazon SQS Developer Guide. Note the following: • Every message must have a unique MessageDeduplicationId. • You may provide a MessageDeduplicationId explicitly. • If you aren't able to provide a MessageDeduplicationId and you enable ContentBasedDeduplication for your queue, Amazon SQS uses a SHA-256 hash
sqs-api-033
sqs-api.pdf
33
139 Amazon Simple Queue Service API Reference • SqsManagedSseEnabled – Enables server-side queue encryption using SQS owned encryption keys. Only one server-side encryption option is supported per queue (for example, SSE-KMS or SSE-SQS). The following attribute applies only to FIFO (first-in-first-out) queues: • ContentBasedDeduplication – Enables content-based deduplication. For more information, see Exactly-once processing in the Amazon SQS Developer Guide. Note the following: • Every message must have a unique MessageDeduplicationId. • You may provide a MessageDeduplicationId explicitly. • If you aren't able to provide a MessageDeduplicationId and you enable ContentBasedDeduplication for your queue, Amazon SQS uses a SHA-256 hash to generate the MessageDeduplicationId using the body of the message (but not the attributes of the message). • If you don't provide a MessageDeduplicationId and the queue doesn't have ContentBasedDeduplication set, the action fails with an error. • If the queue has ContentBasedDeduplication set, your MessageDeduplicationId overrides the generated one. • When ContentBasedDeduplication is in effect, messages with identical content sent within the deduplication interval are treated as duplicates and only one copy of the message is delivered. • If you send one message with ContentBasedDeduplication enabled and then another message with a MessageDeduplicationId that is the same as the one generated for the first MessageDeduplicationId, the two messages are treated as duplicates and only one copy of the message is delivered. The following attributes apply only to high throughput for FIFO queues: • DeduplicationScope – Specifies whether message deduplication occurs at the message group or queue level. Valid values are messageGroup and queue. • FifoThroughputLimit – Specifies whether the FIFO queue throughput quota applies to the entire queue or per message group. Valid values are perQueue and perMessageGroupId. The perMessageGroupId value is allowed only when the value for DeduplicationScope is messageGroup. To enable high throughput for FIFO queues, do the following: Request Parameters API Version 2012-11-05 140 Amazon Simple Queue Service API Reference • Set DeduplicationScope to messageGroup. • Set FifoThroughputLimit to perMessageGroupId. If you set these attributes to anything other than the values shown for enabling high throughput, normal throughput is in effect and deduplication occurs as specified. For information on throughput quotas, see Quotas related to messages in the Amazon SQS Developer Guide. Type: String to string map Valid Keys: All | Policy | VisibilityTimeout | MaximumMessageSize | MessageRetentionPeriod | ApproximateNumberOfMessages | ApproximateNumberOfMessagesNotVisible | CreatedTimestamp | LastModifiedTimestamp | QueueArn | ApproximateNumberOfMessagesDelayed | DelaySeconds | ReceiveMessageWaitTimeSeconds | RedrivePolicy | FifoQueue | ContentBasedDeduplication | KmsMasterKeyId | KmsDataKeyReusePeriodSeconds | DeduplicationScope | FifoThroughputLimit | RedriveAllowPolicy | SqsManagedSseEnabled Required: Yes QueueUrl The URL of the Amazon SQS queue whose attributes are set. Queue URLs and names are case-sensitive. Type: String Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. Response Elements API Version 2012-11-05 141 API Reference Amazon Simple Queue Service InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidAttributeName The specified attribute doesn't exist. HTTP Status Code: 400 InvalidAttributeValue A queue attribute value is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 OverLimit The specified action violates a limit. For example, ReceiveMessage returns this error if the maximum number of in flight messages is reached and AddPermission returns this error if the maximum number of permissions for the queue is reached. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. Errors API Version 2012-11-05 142 Amazon Simple Queue Service HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples API Reference The following example query request sets a policy that gives all users ReceiveMessage permission for a queue named MyQueue. For more examples of policies, see Custom Amazon SQS Access Policy Language Examples in the Amazon SQS Developer Guide. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SetQueueAtrributes X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Attributes": { "Policy": "{\"Version\":\"2012-10-17\",\"Id\":\"Policy1677095510157\", \"Statement\":[{\"Sid\":\"Stmt1677095506939\",\"Effect\":\"Allow\",\"Principal \":\"*\",\"Action\":\"sqs:ReceiveMessage\",\"Resource\":\"arn:aws:sqs:us- east-1:555555555555:MyQueue6\"}]}" } } Sample Response HTTP/1.1 200 OK Examples API Version 2012-11-05 143 Amazon Simple Queue Service API Reference x-amzn-RequestId: <requestId> Content-Length:
sqs-api-034
sqs-api.pdf
34
of policies, see Custom Amazon SQS Access Policy Language Examples in the Amazon SQS Developer Guide. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SetQueueAtrributes X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Attributes": { "Policy": "{\"Version\":\"2012-10-17\",\"Id\":\"Policy1677095510157\", \"Statement\":[{\"Sid\":\"Stmt1677095506939\",\"Effect\":\"Allow\",\"Principal \":\"*\",\"Action\":\"sqs:ReceiveMessage\",\"Resource\":\"arn:aws:sqs:us- east-1:555555555555:MyQueue6\"}]}" } } Sample Response HTTP/1.1 200 OK Examples API Version 2012-11-05 143 Amazon Simple Queue Service API Reference x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: 0 Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=SetQueueAttributes &Attribute.Name=Policy &Attribute.Value=%7B%22Version%22%3A%222012-10-17%22%2C%22Id%22%3A%22UseCase1%22%2C %22Statement%22%3A%5B%7B%22Sid%22%3A%22Queue1ReceiveMessage%22%2C%22Effect %22%3A%22Allow%22%2C%22Principal%22%3A%7B%22AWS%22%3A%22*%22%7D%2C%22Action %22%3A%22SQS%3AReceiveMessage%22%2C%22Resource%22%3A%22arn%3Aaws%3Asqs%3Aus- east-1%3A555555555555%3AMyQueue6%22%7D%5D%7D Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <SetQueueAttributesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>5798727f-61f0-5457-99f0-2e0fa7fce329</RequestId> </ResponseMetadata> </SetQueueAttributesResponse> Example The following example query request sets the visibility timeout to 35 seconds for a queue named MyQueue. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Examples API Version 2012-11-05 144 Amazon Simple Queue Service API Reference Note An Amazon SQS message has three basic states: 1. Sent to a queue by a producer. 2. Received from the queue by a consumer. 3. Deleted from the queue. A message is considered to be stored after it is sent to a queue by a producer, but not yet received from the queue by a consumer (that is, between states 1 and 2). There is no limit to the number of stored messages. A message is considered to be in flight after it is received from a queue by a consumer, but not yet deleted from the queue (that is, between states 2 and 3). There is a limit to the number of in flight messages. Limits that apply to in flight messages are unrelated to the unlimited number of stored messages. For most standard queues (depending on queue traffic and message backlog), there can be a maximum of approximately 120,000 in flight messages (received from a queue by a consumer, but not yet deleted from the queue). If you reach this limit, Amazon SQS returns the OverLimit error message. To avoid reaching the limit, you should delete messages from the queue after they're processed. You can also increase the number of queues you use to process your messages. To request a limit increase, file a support request. For FIFO queues, there can be a maximum of 120,000 in flight messages (received from a queue by a consumer, but not yet deleted from the queue). If you reach this limit, Amazon SQS returns no error messages. Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SetQueueAtrributes X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { Examples API Version 2012-11-05 145 Amazon Simple Queue Service API Reference "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Attributes": { "VisibilityTimeout": "35" } } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: 0 Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=SetQueueAttributes &Attribute.Name=VisibilityTimeout &Attribute.Value=35 Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <SetQueueAttributesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>e5cca473-4fc0-4198-a451-8abb94d02c75</RequestId> </ResponseMetadata> </SetQueueAttributesResponse> Examples API Version 2012-11-05 146 Amazon Simple Queue Service Example API Reference The following example sets a queue named MyDeadLetterQueue as the dead-letter queue for a queue name MySourceQueue by calling the SetQueueAttributes action with the configuration details for the dead-letter queue. Note Queue URLs and names are case-sensitive. Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SetQueueAtrributes X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Attributes": { "RedrivePolicy": "{\"maxReceiveCount\":\"5\",\"deadLetterTargetArn\": \"arn:aws:sqs:us-east-1:555555555555:MyDeadLetterQueue\"}" } } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: 0 Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Examples API Version 2012-11-05 147 Amazon Simple Queue Service Sample Request API Reference POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=SetQueueAttributes &Attribute.Name=RedrivePolicy &Attribute.Value=%7B%22maxReceiveCount%22%3A%225%22%2C%20%22deadLetterTargetArn%22%3A %22arn%3Aaws%3Asqs%3Aus-east-1%3A555555555555%3AMyDeadLetterQueue%22%7D Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <SetQueueAttributesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>627e8ac6-73bf-515c-a359-d654eebaa6c3</RequestId> </ResponseMetadata> </SetQueueAttributesResponse> Example The following example enables long polling by calling the SetQueueAttributes action with the ReceiveMessageWaitTimeSeconds parameter set to 20 seconds. Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SetQueueAtrributes X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { Examples API Version 2012-11-05 148 Amazon Simple Queue Service API Reference "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Attributes": { "ReceiveMessageWaitTimeSeconds": "20" } } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: 0 Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection:
sqs-api-035
sqs-api.pdf
35
</ResponseMetadata> </SetQueueAttributesResponse> Example The following example enables long polling by calling the SetQueueAttributes action with the ReceiveMessageWaitTimeSeconds parameter set to 20 seconds. Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SetQueueAtrributes X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { Examples API Version 2012-11-05 148 Amazon Simple Queue Service API Reference "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Attributes": { "ReceiveMessageWaitTimeSeconds": "20" } } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: 0 Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=SetQueueAttributes &Attribute.Name=ReceiveMessageWaitTimeSeconds &Attribute.Value=20 Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <SetQueueAttributesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>3949c1a7-1e69-564c-ad00-9d3583174f09</RequestId> </ResponseMetadata> </SetQueueAttributesResponse> Examples API Version 2012-11-05 149 Amazon Simple Queue Service Example API Reference The following example changes an existing queue into a delay queue by calling the SetQueueAttributes action with the DelaySeconds attribute set to 45 seconds. Changing the DelaySeconds attribute from its default value of 0 to a positive integer less than or equal to 900 changes the queue into a delay queue. Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.SetQueueAtrributes X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Attributes": { "DelaySeconds": "45" } } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: 0 Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com Examples API Version 2012-11-05 150 API Reference Amazon Simple Queue Service X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=SetQueueAttributes &Attribute.Name=DelaySeconds &Attribute.Value=45 Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <SetQueueAttributesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>e4761152-39b6-556e-84a0-4dc0a78f4927</RequestId> </ResponseMetadata> </SetQueueAttributesResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 151 Amazon Simple Queue Service API Reference StartMessageMoveTask Starts an asynchronous task to move messages from a specified source queue to a specified destination queue. Note • This action is currently limited to supporting message redrive from queues that are configured as dead-letter queues (DLQs) of other Amazon SQS queues only. Non-SQS queue sources of dead-letter queues, such as AWS Lambda or Amazon SNS topics, are currently not supported. • In dead-letter queues redrive context, the StartMessageMoveTask the source queue is the DLQ, while the destination queue can be the original source queue (from which the messages were driven to the dead-letter-queue), or a custom destination queue. • Only one active message movement task is supported per queue at any given time. Request Syntax { "DestinationArn": "string", "MaxNumberOfMessagesPerSecond": number, "SourceArn": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. DestinationArn The ARN of the queue that receives the moved messages. You can use this field to specify the destination queue where you would like to redrive messages. If this field is left blank, the messages will be redriven back to their respective original source queues. Type: String StartMessageMoveTask API Version 2012-11-05 152 Amazon Simple Queue Service Required: No MaxNumberOfMessagesPerSecond API Reference The number of messages to be moved per second (the message movement rate). You can use this field to define a fixed message movement rate. The maximum value for messages per second is 500. If this field is left blank, the system will optimize the rate based on the queue message backlog size, which may vary throughout the duration of the message movement task. Type: Integer Required: No SourceArn The ARN of the queue that contains the messages to be moved to another queue. Currently, only ARNs of dead-letter queues (DLQs) whose sources are other Amazon SQS queues are accepted. DLQs whose sources are non-SQS queues, such as AWS Lambda or Amazon SNS topics, are not currently supported. Type: String Required: Yes Response Syntax { "TaskHandle": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. TaskHandle An identifier associated with a message movement task. You can use this identifier to cancel a specified message movement task using the CancelMessageMoveTask action. Type: String Response Syntax API Version 2012-11-05 153 Amazon Simple Queue Service Errors API Reference For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or
sqs-api-036
sqs-api.pdf
36
} Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. TaskHandle An identifier associated with a message movement task. You can use this identifier to cancel a specified message movement task using the CancelMessageMoveTask action. Type: String Response Syntax API Version 2012-11-05 153 Amazon Simple Queue Service Errors API Reference For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 ResourceNotFoundException One or more specified resources don't exist. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples Example Using AWS query protocol Errors API Version 2012-11-05 154 Amazon Simple Queue Service API Reference The following example query starts a message move task on a dead-letter queue MyDeadLetterQueue to its source queue, with a limit of 10 messages per second. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Examples of Signed Signature Version 4 Requests in the AWS General Reference. Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=StartMessageMoveTask &SourceArn=arn:aws:sqs:us-east-1:555555555555:MyDeadLetterQueue &MaxNumberOfMessagesPerSecond=10 Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <StartMessageMoveTaskResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <StartMessageMoveTaskResult> <TaskHandle>eyJ0YXNrSWQiOiJkYzE2OWUwNC0wZTU1LTQ0ZDItYWE5MC1jMDgwY2ExZjM2ZjciLCJzb3VyY2VBcm4iOiJhcm46YXdzOnNxczp1cy1lYXN0LTE6MTc3NzE1MjU3NDM2Ok15RGVhZExldHRlclF1ZXVlIn0=</ TaskHandle> </StartMessageMoveTaskResult> <ResponseMetadata> <RequestId>9b20926c-8b35-5d8e-9559-ce1c22e754dc</RequestId> </ResponseMetadata> </StartMessageMoveTaskResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ See Also API Version 2012-11-05 155 Amazon Simple Queue Service • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2012-11-05 156 Amazon Simple Queue Service TagQueue API Reference Add cost allocation tags to the specified Amazon SQS queue. For an overview, see Tagging Your Amazon SQS Queues in the Amazon SQS Developer Guide. When you use queue tags, keep the following guidelines in mind: • Adding more than 50 tags to a queue isn't recommended. • Tags don't have any semantic meaning. Amazon SQS interprets tags as character strings. • Tags are case-sensitive. • A new tag with a key identical to that of an existing tag overwrites the existing tag. For a full list of tag restrictions, see Quotas related to queues in the Amazon SQS Developer Guide. Note Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. Request Syntax { "QueueUrl": "string", "Tags": { "string" : "string" } } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. QueueUrl The URL of the queue. TagQueue API Version 2012-11-05 157 API Reference Amazon Simple Queue Service Type: String Required: Yes Tags The list of tags to be added to the specified queue. Type: String to string map Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. Response Elements API Version 2012-11-05 158 Amazon Simple Queue Service API Reference • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples This example illustrates one usage of TagQueue. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.TagQueue X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Tags":
sqs-api-037
sqs-api.pdf
37
the queue or for the recipient of the request. Response Elements API Version 2012-11-05 158 Amazon Simple Queue Service API Reference • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples This example illustrates one usage of TagQueue. Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.TagQueue X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "Tags": { "QueueType": "Production" } } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: 0 Date: <Date> Examples API Version 2012-11-05 159 Amazon Simple Queue Service API Reference Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Action=TagQueue &Tag.Key=QueueType &Tag.Value=Production Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> <TagQueueResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>4bc96290-c3b5-5248-aace-3ee0056359b4</RequestId> </ResponseMetadata> </TagQueueResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 See Also API Version 2012-11-05 160 Amazon Simple Queue Service • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2012-11-05 161 Amazon Simple Queue Service UntagQueue API Reference Remove cost allocation tags from the specified Amazon SQS queue. For an overview, see Tagging Your Amazon SQS Queues in the Amazon SQS Developer Guide. Note Cross-account permissions don't apply to this action. For more information, see Grant cross-account permissions to a role and a username in the Amazon SQS Developer Guide. Request Syntax { "QueueUrl": "string", "TagKeys": [ "string" ] } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. QueueUrl The URL of the queue. Type: String Required: Yes TagKeys The list of tags to be removed from the specified queue. Type: Array of strings Required: Yes UntagQueue API Version 2012-11-05 162 Amazon Simple Queue Service Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidAddress The specified ID is invalid. HTTP Status Code: 400 InvalidSecurity The request was not made over HTTPS or did not use SigV4 for signing. HTTP Status Code: 400 QueueDoesNotExist Ensure that the QueueUrl is correct and that the queue has not been deleted. HTTP Status Code: 400 RequestThrottled The request was denied due to request throttling. • Exceeds the permitted request rate for the queue or for the recipient of the request. • Ensure that the request rate is within the Amazon SQS limits for sending messages. For more information, see Amazon SQS quotas in the Amazon SQS Developer Guide. HTTP Status Code: 400 UnsupportedOperation Error code 400. Unsupported operation. HTTP Status Code: 400 Examples The following examples illustrate one usage of UntagQueue. Response Elements API Version 2012-11-05 163 API Reference Amazon Simple Queue Service Example Using AWS JSON protocol (Default) Sample Request POST / HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Target: AmazonSQS.UntagQueue X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/177715257436/MyQueue/", "TagKeys": [ "QueueType" ] } Sample Response HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: 0 Date: <Date> Content-Type: application/x-amz-json-1.0 Example Using AWS query protocol Sample Request POST /177715257436/MyQueue/ HTTP/1.1 Host: sqs.us-east-1.amazonaws.com X-Amz-Date: <Date> Content-Type: application/x-www-form-urlencoded Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Examples API Version 2012-11-05 164 Amazon Simple Queue Service Action=UntagQueue &TagKey=QueueType Sample Response HTTP/1.1 200 OK <?xml version="1.0"?> API Reference <UntagQueueResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> <ResponseMetadata> <RequestId>2b4cc90a-f554-5f5b-a8ca-957a32378232</RequestId> </ResponseMetadata> </UntagQueueResponse> See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 165 Amazon Simple Queue Service Data Types API Reference The Amazon Simple Queue Service API contains several data types that various actions use. This section describes each data type in detail. Note The order of each element in a data type structure is not guaranteed. Applications should not assume a particular order. The following data types are supported: • BatchResultErrorEntry • ChangeMessageVisibilityBatchRequestEntry • ChangeMessageVisibilityBatchResultEntry
sqs-api-038
sqs-api.pdf
38
for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2012-11-05 165 Amazon Simple Queue Service Data Types API Reference The Amazon Simple Queue Service API contains several data types that various actions use. This section describes each data type in detail. Note The order of each element in a data type structure is not guaranteed. Applications should not assume a particular order. The following data types are supported: • BatchResultErrorEntry • ChangeMessageVisibilityBatchRequestEntry • ChangeMessageVisibilityBatchResultEntry • DeleteMessageBatchRequestEntry • DeleteMessageBatchResultEntry • ListMessageMoveTasksResultEntry • Message • MessageAttributeValue • MessageSystemAttributeValue • SendMessageBatchRequestEntry • SendMessageBatchResultEntry API Version 2012-11-05 166 Amazon Simple Queue Service API Reference BatchResultErrorEntry Gives a detailed description of the result of an action on each entry in the request. Contents Code An error code representing why the action failed on this entry. Type: String Required: Yes Id The Id of an entry in a batch request. Type: String Required: Yes SenderFault Specifies whether the error happened due to the caller of the batch API action. Type: Boolean Required: Yes Message A message explaining why the action failed on this entry. Type: String Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ BatchResultErrorEntry API Version 2012-11-05 167 Amazon Simple Queue Service • AWS SDK for Java V2 • AWS SDK for Ruby V3 API Reference See Also API Version 2012-11-05 168 Amazon Simple Queue Service API Reference ChangeMessageVisibilityBatchRequestEntry Encloses a receipt handle and an entry ID for each message in ChangeMessageVisibilityBatch. Contents Id An identifier for this particular receipt handle used to communicate the result. Note The Ids of a batch request need to be unique within a request. This identifier can have up to 80 characters. The following characters are accepted: alphanumeric characters, hyphens(-), and underscores (_). Type: String Required: Yes ReceiptHandle A receipt handle. Type: String Required: Yes VisibilityTimeout The new value (in seconds) for the message's visibility timeout. Type: Integer Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: ChangeMessageVisibilityBatchRequestEntry API Version 2012-11-05 169 Amazon Simple Queue Service • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 API Reference See Also API Version 2012-11-05 170 Amazon Simple Queue Service API Reference ChangeMessageVisibilityBatchResultEntry Encloses the Id of an entry in ChangeMessageVisibilityBatch. Contents Id Represents a message whose visibility timeout has been changed successfully. Type: String Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ChangeMessageVisibilityBatchResultEntry API Version 2012-11-05 171 Amazon Simple Queue Service API Reference DeleteMessageBatchRequestEntry Encloses a receipt handle and an identifier for it. Contents Id The identifier for this particular receipt handle. This is used to communicate the result. Note The Ids of a batch request need to be unique within a request. This identifier can have up to 80 characters. The following characters are accepted: alphanumeric characters, hyphens(-), and underscores (_). Type: String Required: Yes ReceiptHandle A receipt handle. Type: String Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 DeleteMessageBatchRequestEntry API Version 2012-11-05 172 Amazon Simple Queue Service API Reference DeleteMessageBatchResultEntry Encloses the Id of an entry in DeleteMessageBatch. Contents Id Represents a successfully deleted message. Type: String Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 DeleteMessageBatchResultEntry API Version 2012-11-05 173 Amazon Simple Queue Service API Reference ListMessageMoveTasksResultEntry Contains the details of a message movement task. Contents ApproximateNumberOfMessagesMoved The approximate number of messages already moved to the destination queue. Type: Long Required: No ApproximateNumberOfMessagesToMove The number of messages to be moved from the source queue. This number is obtained at the time of starting the message movement task and is only included after the message movement task is selected to start. Type: Long Required: No DestinationArn The ARN of the destination queue if it has been specified in the StartMessageMoveTask request. If a DestinationArn has not been specified in the StartMessageMoveTask request, this field value will be NULL. Type: String Required: No FailureReason The task failure reason (only included if the task status is FAILED). Type: String Required: No ListMessageMoveTasksResultEntry API Version 2012-11-05 174 Amazon Simple
sqs-api-039
sqs-api.pdf
39
of messages to be moved from the source queue. This number is obtained at the time of starting the message movement task and is only included after the message movement task is selected to start. Type: Long Required: No DestinationArn The ARN of the destination queue if it has been specified in the StartMessageMoveTask request. If a DestinationArn has not been specified in the StartMessageMoveTask request, this field value will be NULL. Type: String Required: No FailureReason The task failure reason (only included if the task status is FAILED). Type: String Required: No ListMessageMoveTasksResultEntry API Version 2012-11-05 174 Amazon Simple Queue Service API Reference MaxNumberOfMessagesPerSecond The number of messages to be moved per second (the message movement rate), if it has been specified in the StartMessageMoveTask request. If a MaxNumberOfMessagesPerSecond has not been specified in the StartMessageMoveTask request, this field value will be NULL. Type: Integer Required: No SourceArn The ARN of the queue that contains the messages to be moved to another queue. Type: String Required: No StartedTimestamp The timestamp of starting the message movement task. Type: Long Required: No Status The status of the message movement task. Possible values are: RUNNING, COMPLETED, CANCELLING, CANCELLED, and FAILED. Type: String Required: No TaskHandle An identifier associated with a message movement task. When this field is returned in the response of the ListMessageMoveTasks action, it is only populated for tasks that are in RUNNING status. Type: String Required: No Contents API Version 2012-11-05 175 Amazon Simple Queue Service See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2012-11-05 176 Amazon Simple Queue Service Message An Amazon SQS message. Contents Attributes API Reference A map of the attributes requested in ReceiveMessage to their respective values. Supported attributes: • ApproximateReceiveCount • ApproximateFirstReceiveTimestamp • MessageDeduplicationId • MessageGroupId • SenderId • SentTimestamp • SequenceNumber ApproximateFirstReceiveTimestamp and SentTimestamp are each returned as an integer representing the epoch time in milliseconds. Type: String to string map Valid Keys: All | SenderId | SentTimestamp | ApproximateReceiveCount | ApproximateFirstReceiveTimestamp | SequenceNumber | MessageDeduplicationId | MessageGroupId | AWSTraceHeader | DeadLetterQueueSourceArn Required: No Body The message's contents (not URL-encoded). Type: String Required: No Message API Version 2012-11-05 177 Amazon Simple Queue Service MD5OfBody API Reference An MD5 digest of the non-URL-encoded message body string. Type: String Required: No MD5OfMessageAttributes An MD5 digest of the non-URL-encoded message attribute string. You can use this attribute to verify that Amazon SQS received the message correctly. Amazon SQS URL-decodes the message before creating the MD5 digest. For information about MD5, see RFC1321. Type: String Required: No MessageAttributes Each message attribute consists of a Name, Type, and Value. For more information, see Amazon SQS message attributes in the Amazon SQS Developer Guide. Type: String to MessageAttributeValue object map Required: No MessageId A unique identifier for the message. A MessageIdis considered unique across all AWS accounts for an extended period of time. Type: String Required: No ReceiptHandle An identifier associated with the act of receiving the message. A new receipt handle is returned every time you receive a message. When deleting a message, you provide the last received receipt handle to delete the message. Type: String Required: No Contents API Version 2012-11-05 178 Amazon Simple Queue Service See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2012-11-05 179 Amazon Simple Queue Service API Reference MessageAttributeValue The user-specified message attribute value. For string data types, the Value attribute has the same restrictions on the content as the message body. For more information, see SendMessage. Name, type, value and the message body must not be empty or null. All parts of the message attribute, including Name, Type, and Value, are part of the message size restriction (256 KiB or 262,144 bytes). Contents DataType Amazon SQS supports the following logical data types: String, Number, and Binary. For the Number data type, you must use StringValue. You can also append custom labels. For more information, see Amazon SQS Message Attributes in the Amazon SQS Developer Guide. Type: String Required: Yes BinaryListValues Not implemented. Reserved for future use. Type: Array of Base64-encoded binary data objects Required: No BinaryValue Binary type attributes can store any binary data, such as compressed data, encrypted data, or images. Type: Base64-encoded binary data object Required: No StringListValues Not implemented. Reserved for future use. MessageAttributeValue API Version 2012-11-05 180 Amazon Simple Queue Service Type: Array of strings Required: No StringValue API Reference Strings are Unicode with UTF-8 binary encoding. For a list
sqs-api-040
sqs-api.pdf
40
StringValue. You can also append custom labels. For more information, see Amazon SQS Message Attributes in the Amazon SQS Developer Guide. Type: String Required: Yes BinaryListValues Not implemented. Reserved for future use. Type: Array of Base64-encoded binary data objects Required: No BinaryValue Binary type attributes can store any binary data, such as compressed data, encrypted data, or images. Type: Base64-encoded binary data object Required: No StringListValues Not implemented. Reserved for future use. MessageAttributeValue API Version 2012-11-05 180 Amazon Simple Queue Service Type: Array of strings Required: No StringValue API Reference Strings are Unicode with UTF-8 binary encoding. For a list of code values, see ASCII Printable Characters. Type: String Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2012-11-05 181 Amazon Simple Queue Service API Reference MessageSystemAttributeValue The user-specified message system attribute value. For string data types, the Value attribute has the same restrictions on the content as the message body. For more information, see SendMessage. Name, type, value and the message body must not be empty or null. Contents DataType Amazon SQS supports the following logical data types: String, Number, and Binary. For the Number data type, you must use StringValue. You can also append custom labels. For more information, see Amazon SQS Message Attributes in the Amazon SQS Developer Guide. Type: String Required: Yes BinaryListValues Not implemented. Reserved for future use. Type: Array of Base64-encoded binary data objects Required: No BinaryValue Binary type attributes can store any binary data, such as compressed data, encrypted data, or images. Type: Base64-encoded binary data object Required: No StringListValues Not implemented. Reserved for future use. Type: Array of strings MessageSystemAttributeValue API Version 2012-11-05 182 Amazon Simple Queue Service Required: No StringValue API Reference Strings are Unicode with UTF-8 binary encoding. For a list of code values, see ASCII Printable Characters. Type: String Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2012-11-05 183 Amazon Simple Queue Service API Reference SendMessageBatchRequestEntry Contains the details of a single Amazon SQS message along with an Id. Contents Id An identifier for a message in this batch used to communicate the result. Note The Ids of a batch request need to be unique within a request. This identifier can have up to 80 characters. The following characters are accepted: alphanumeric characters, hyphens(-), and underscores (_). Type: String Required: Yes MessageBody The body of the message. Type: String Required: Yes DelaySeconds The length of time, in seconds, for which a specific message is delayed. Valid values: 0 to 900. Maximum: 15 minutes. Messages with a positive DelaySeconds value become available for processing after the delay period is finished. If you don't specify a value, the default value for the queue is applied. Note When you set FifoQueue, you can't set DelaySeconds per message. You can set this parameter only on a queue level. SendMessageBatchRequestEntry API Version 2012-11-05 184 Amazon Simple Queue Service Type: Integer Required: No MessageAttributes API Reference Each message attribute consists of a Name, Type, and Value. For more information, see Amazon SQS message attributes in the Amazon SQS Developer Guide. Type: String to MessageAttributeValue object map Required: No MessageDeduplicationId This parameter applies only to FIFO (first-in-first-out) queues. The token used for deduplication of messages within a 5-minute minimum deduplication interval. If a message with a particular MessageDeduplicationId is sent successfully, subsequent messages with the same MessageDeduplicationId are accepted successfully but aren't delivered. For more information, see Exactly-once processing in the Amazon SQS Developer Guide. • Every message must have a unique MessageDeduplicationId, • You may provide a MessageDeduplicationId explicitly. • If you aren't able to provide a MessageDeduplicationId and you enable ContentBasedDeduplication for your queue, Amazon SQS uses a SHA-256 hash to generate the MessageDeduplicationId using the body of the message (but not the attributes of the message). • If you don't provide a MessageDeduplicationId and the queue doesn't have ContentBasedDeduplication set, the action fails with an error. • If the queue has ContentBasedDeduplication set, your MessageDeduplicationId overrides the generated one. • When ContentBasedDeduplication is in effect, messages with identical content sent within the deduplication interval are treated as duplicates and only one copy of the message is delivered. • If you send one message with ContentBasedDeduplication enabled and then another message with a MessageDeduplicationId that is the same as the one generated for the first MessageDeduplicationId, the two messages are treated as duplicates and only one copy of the message is delivered. Contents API Version 2012-11-05 185
sqs-api-041
sqs-api.pdf
41
doesn't have ContentBasedDeduplication set, the action fails with an error. • If the queue has ContentBasedDeduplication set, your MessageDeduplicationId overrides the generated one. • When ContentBasedDeduplication is in effect, messages with identical content sent within the deduplication interval are treated as duplicates and only one copy of the message is delivered. • If you send one message with ContentBasedDeduplication enabled and then another message with a MessageDeduplicationId that is the same as the one generated for the first MessageDeduplicationId, the two messages are treated as duplicates and only one copy of the message is delivered. Contents API Version 2012-11-05 185 Amazon Simple Queue Service API Reference Note The MessageDeduplicationId is available to the consumer of the message (this can be useful for troubleshooting delivery issues). If a message is sent successfully but the acknowledgement is lost and the message is resent with the same MessageDeduplicationId after the deduplication interval, Amazon SQS can't detect duplicate messages. Amazon SQS continues to keep track of the message deduplication ID even after the message is received and deleted. The length of MessageDeduplicationId is 128 characters. MessageDeduplicationId can contain alphanumeric characters (a-z, A-Z, 0-9) and punctuation (!"#$%&'()*+,-./:;<=>? @[\]^_`{|}~). For best practices of using MessageDeduplicationId, see Using the MessageDeduplicationId Property in the Amazon SQS Developer Guide. Type: String Required: No MessageGroupId This parameter applies only to FIFO (first-in-first-out) queues. The tag that specifies that a message belongs to a specific message group. Messages that belong to the same message group are processed in a FIFO manner (however, messages in different message groups might be processed out of order). To interleave multiple ordered streams within a single queue, use MessageGroupId values (for example, session data for multiple users). In this scenario, multiple consumers can process the queue, but the session data of each user is processed in a FIFO fashion. • You must associate a non-empty MessageGroupId with a message. If you don't provide a MessageGroupId, the action fails. • ReceiveMessage might return messages with multiple MessageGroupId values. For each MessageGroupId, the messages are sorted by time sent. The caller can't specify a MessageGroupId. The length of MessageGroupId is 128 characters. Valid values: alphanumeric characters and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~). Contents API Version 2012-11-05 186 Amazon Simple Queue Service API Reference For best practices of using MessageGroupId, see Using the MessageGroupId Property in the Amazon SQS Developer Guide. Important MessageGroupId is required for FIFO queues. You can't use it for Standard queues. Type: String Required: No MessageSystemAttributes The message system attribute to send Each message system attribute consists of a Name, Type, and Value. Important • Currently, the only supported message system attribute is AWSTraceHeader. Its type must be String and its value must be a correctly formatted AWS X-Ray trace header string. • The size of a message system attribute doesn't count towards the total size of a message. Type: String to MessageSystemAttributeValue object map Valid Keys: AWSTraceHeader Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 See Also API Version 2012-11-05 187 Amazon Simple Queue Service • AWS SDK for Ruby V3 API Reference See Also API Version 2012-11-05 188 Amazon Simple Queue Service API Reference SendMessageBatchResultEntry Encloses a MessageId for a successfully-enqueued message in a SendMessageBatch. Contents Id An identifier for the message in this batch. Type: String Required: Yes MD5OfMessageBody An MD5 digest of the non-URL-encoded message body string. You can use this attribute to verify that Amazon SQS received the message correctly. Amazon SQS URL-decodes the message before creating the MD5 digest. For information about MD5, see RFC1321. Type: String Required: Yes MessageId An identifier for the message. Type: String Required: Yes MD5OfMessageAttributes An MD5 digest of the non-URL-encoded message attribute string. You can use this attribute to verify that Amazon SQS received the message correctly. Amazon SQS URL-decodes the message before creating the MD5 digest. For information about MD5, see RFC1321. Type: String Required: No SendMessageBatchResultEntry API Version 2012-11-05 189 Amazon Simple Queue Service API Reference MD5OfMessageSystemAttributes An MD5 digest of the non-URL-encoded message system attribute string. You can use this attribute to verify that Amazon SQS received the message correctly. Amazon SQS URL-decodes the message before creating the MD5 digest. For information about MD5, see RFC1321. Type: String Required: No SequenceNumber This parameter applies only to FIFO (first-in-first-out) queues. The large, non-consecutive number that Amazon SQS assigns to each message. The length of SequenceNumber is 128 bits. As SequenceNumber continues to increase for a particular MessageGroupId. Type: String Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API
sqs-api-042
sqs-api.pdf
42
correctly. Amazon SQS URL-decodes the message before creating the MD5 digest. For information about MD5, see RFC1321. Type: String Required: No SequenceNumber This parameter applies only to FIFO (first-in-first-out) queues. The large, non-consecutive number that Amazon SQS assigns to each message. The length of SequenceNumber is 128 bits. As SequenceNumber continues to increase for a particular MessageGroupId. Type: String Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2012-11-05 190 Amazon Simple Queue Service API Reference Common Parameters The following list contains the parameters that all actions use for signing Signature Version 4 requests with a query string. Any action-specific parameters are listed in the topic for that action. For more information about Signature Version 4, see Signing AWS API requests in the IAM User Guide. Action The action to be performed. Type: string Required: Yes Version The API version that the request is written for, expressed in the format YYYY-MM-DD. Type: string Required: Yes X-Amz-Algorithm The hash algorithm that you used to create the request signature. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. Type: string Valid Values: AWS4-HMAC-SHA256 Required: Conditional X-Amz-Credential The credential scope value, which is a string that includes your access key, the date, the region you are targeting, the service you are requesting, and a termination string ("aws4_request"). The value is expressed in the following format: access_key/YYYYMMDD/region/service/ aws4_request. API Version 2012-11-05 191 Amazon Simple Queue Service API Reference For more information, see Create a signed AWS API request in the IAM User Guide. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. Type: string Required: Conditional X-Amz-Date The date that is used to create the signature. The format must be ISO 8601 basic format (YYYYMMDD'T'HHMMSS'Z'). For example, the following date time is a valid X-Amz-Date value: 20120325T120000Z. Condition: X-Amz-Date is optional for all requests; it can be used to override the date used for signing requests. If the Date header is specified in the ISO 8601 basic format, X-Amz-Date is not required. When X-Amz-Date is used, it always overrides the value of the Date header. For more information, see Elements of an AWS API request signature in the IAM User Guide. Type: string Required: Conditional X-Amz-Security-Token The temporary security token that was obtained through a call to AWS Security Token Service (AWS STS). For a list of services that support temporary security credentials from AWS STS, see AWS services that work with IAM in the IAM User Guide. Condition: If you're using temporary security credentials from AWS STS, you must include the security token. Type: string Required: Conditional X-Amz-Signature Specifies the hex-encoded signature that was calculated from the string to sign and the derived signing key. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. API Version 2012-11-05 192 Amazon Simple Queue Service Type: string Required: Conditional X-Amz-SignedHeaders API Reference Specifies all the HTTP headers that were included as part of the canonical request. For more information about specifying signed headers, see Create a signed AWS API request in the IAM User Guide. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. Type: string Required: Conditional API Version 2012-11-05 193 Amazon Simple Queue Service API Reference Common Errors This section lists the errors common to the API actions of all AWS services. For errors specific to an API action for this service, see the topic for that API action. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 400 IncompleteSignature The request signature does not conform to AWS standards. HTTP Status Code: 400 InternalFailure The request processing has failed because of an unknown error, exception or failure. HTTP Status Code: 500 InvalidAction The action or operation requested is invalid. Verify that the action is typed correctly. HTTP Status Code: 400 InvalidClientTokenId The X.509 certificate or AWS access key ID provided does not exist in our records. HTTP Status Code: 403 InvalidParameterCombination Parameters that must not be used together were used together. HTTP Status Code: 400 InvalidParameterValue An invalid or out-of-range value was supplied for the input parameter. HTTP Status Code: 400 API Version 2012-11-05 194 Amazon Simple Queue Service InvalidQueryParameter API Reference The AWS query string is malformed or does not adhere to AWS standards. HTTP Status Code: 400 MalformedQueryString The query string contains a syntax error. HTTP Status Code: 404 MissingAction The request is missing an action or a required parameter.
sqs-api-043
sqs-api.pdf
43
X.509 certificate or AWS access key ID provided does not exist in our records. HTTP Status Code: 403 InvalidParameterCombination Parameters that must not be used together were used together. HTTP Status Code: 400 InvalidParameterValue An invalid or out-of-range value was supplied for the input parameter. HTTP Status Code: 400 API Version 2012-11-05 194 Amazon Simple Queue Service InvalidQueryParameter API Reference The AWS query string is malformed or does not adhere to AWS standards. HTTP Status Code: 400 MalformedQueryString The query string contains a syntax error. HTTP Status Code: 404 MissingAction The request is missing an action or a required parameter. HTTP Status Code: 400 MissingAuthenticationToken The request must contain either a valid (registered) AWS access key ID or X.509 certificate. HTTP Status Code: 403 MissingParameter A required parameter for the specified action is not supplied. HTTP Status Code: 400 NotAuthorized You do not have permission to perform this action. HTTP Status Code: 400 OptInRequired The AWS access key ID needs a subscription for the service. HTTP Status Code: 403 RequestExpired The request reached the service more than 15 minutes after the date stamp on the request or more than 15 minutes after the request expiration date (such as for pre-signed URLs), or the date stamp on the request is more than 15 minutes in the future. API Version 2012-11-05 195 API Reference Amazon Simple Queue Service HTTP Status Code: 400 ServiceUnavailable The request has failed due to a temporary failure of the server. HTTP Status Code: 503 ThrottlingException The request was denied due to request throttling. HTTP Status Code: 403 ValidationError The input fails to satisfy the constraints specified by an AWS service. HTTP Status Code: 400 API Version 2012-11-05 196
sqs-dg-001
sqs-dg.pdf
1
Developer Guide Amazon Simple Queue Service Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon Simple Queue Service Developer Guide Amazon Simple Queue Service: Developer Guide Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon. Amazon Simple Queue Service Table of Contents Developer Guide What is Amazon SQS? ..................................................................................................................... 1 Benefits of using Amazon SQS .................................................................................................................. 1 Basic architecture ......................................................................................................................................... 1 Distributed queues .................................................................................................................................. 2 Message lifecycle ..................................................................................................................................... 2 Differences between Amazon SQS, Amazon MQ, and Amazon SNS .................................................. 4 Getting started ................................................................................................................................ 6 Setting up ...................................................................................................................................................... 6 Step 1: Create an AWS account and IAM user .................................................................................. 6 Step 2: Grant programmatic access .................................................................................................... 8 Step 3: Get ready to use the example code .................................................................................... 10 Next steps ............................................................................................................................................... 10 Understanding the Amazon SQS console ............................................................................................. 10 Queue types ................................................................................................................................................ 12 Implementing request-response systems in Amazon SQS ........................................................... 14 Creating a standard queue ....................................................................................................................... 15 Creating a queue ................................................................................................................................... 15 Sending a message using a standard queue ................................................................................... 17 Creating a FIFO queue .............................................................................................................................. 18 Create a queue ...................................................................................................................................... 18 Sending a message using a FIFO queue .......................................................................................... 20 Common tasks ............................................................................................................................................ 21 Managing a queue ......................................................................................................................... 23 Editing a queue .......................................................................................................................................... 23 Receiving and deleting a message ......................................................................................................... 23 Confirming a queue is empty .................................................................................................................. 25 Deleting a queue ........................................................................................................................................ 26 Purging a queue ......................................................................................................................................... 27 Standard queues ............................................................................................................................ 28 Amazon SQS at-least-once delivery ....................................................................................................... 28 Queue and message identifiers ............................................................................................................... 29 Identifiers for standard queues ......................................................................................................... 29 FIFO queues ................................................................................................................................... 31 FIFO queue key terms ............................................................................................................................... 32 iii Amazon Simple Queue Service Developer Guide FIFO delivery logic ..................................................................................................................................... 33 Sending messages ................................................................................................................................ 33 Receiving messages .............................................................................................................................. 34 Retrying multiple times ....................................................................................................................... 35 Additional notes on FIFO behavior ................................................................................................... 36 Examples for better understanding .................................................................................................. 36 Exactly-once processing ............................................................................................................................ 37 Moving from a standard queue to a FIFO queue ................................................................................ 37 FIFO queue and Lambda concurrency behavior .................................................................................. 39 FIFO queue message grouping .......................................................................................................... 39 Lambda concurrency with FIFO queues ........................................................................................... 39 Use case example ................................................................................................................................. 40 High throughput for FIFO queues .......................................................................................................... 40 Use cases ................................................................................................................................................ 41 Partitions and data distribution ........................................................................................................ 41 Enabling high throughput for FIFO queues .................................................................................... 44 Queue and message identifiers ............................................................................................................... 45 Identifiers for FIFO queues ................................................................................................................. 29 Additional identifiers for FIFO queues ............................................................................................. 46 Quotas ............................................................................................................................................ 48 FIFO queue quotas ..................................................................................................................................... 48 Amazon SQS quotas ............................................................................................................................. 48 Standard queue quotas ............................................................................................................................. 49 Message quotas .......................................................................................................................................... 51 Policy quotas ............................................................................................................................................... 57 Features and capabilities .............................................................................................................. 59 Dead-letter queues .................................................................................................................................... 59 Using policies for dead-letter queues .............................................................................................. 60 Understanding message retention periods for dead-letter queues ............................................ 60 Configuring a dead-letter queue ....................................................................................................... 60 Configuring a dead-letter queue redrive ......................................................................................... 61 CloudTrail update and permission requirements ........................................................................... 68 Creating alarms for dead-letter queues using Amazon CloudWatch ......................................... 72 Message metadata for Amazon SQS ..................................................................................................... 72 Message attributes ............................................................................................................................... 72 Message system attributes ................................................................................................................. 77 iv Amazon Simple Queue Service Developer Guide Resources required to process messages .............................................................................................. 77 List queue pagination ................................................................................................................................ 78 Cost allocation tags ................................................................................................................................... 78 Short and long polling ............................................................................................................................. 79 Consuming messages using short polling ....................................................................................... 80 Consuming messages using long polling ........................................................................................ 80 Differences between long and short polling .................................................................................. 81 Visibility timeout ........................................................................................................................................ 81 Visibility timeout use cases ................................................................................................................ 82 Setting and adjusting the visibility timeout ................................................................................... 83 In flight messages and quotas ........................................................................................................... 83 Understanding visibility timeout in standard and FIFO queues .................................................. 84 Handling failures ................................................................................................................................... 84 Changing and terminating visibility timeout .................................................................................. 84 Best practices ......................................................................................................................................... 85 Delay queues ............................................................................................................................................... 85 Temporary queues ..................................................................................................................................... 87 Virtual queues ....................................................................................................................................... 87 Request-response messaging pattern (virtual queues) ................................................................. 88 Example scenario: Processing a login request ................................................................................ 89 Cleaning up queues .............................................................................................................................. 91 Message timers ........................................................................................................................................... 92 Accessing EventBridge pipes .................................................................................................................... 92 Managing large messages ........................................................................................................................ 94 Using the Extended Client Library for Java .................................................................................... 94 Using the Extended Client Library for Python ............................................................................. 100 Configuring Amazon SQS ............................................................................................................ 104 ABAC for Amazon SQS ........................................................................................................................... 104 What is ABAC? ..................................................................................................................................... 104 Why should I use ABAC in Amazon SQS? ...................................................................................... 105 Tagging for access control ................................................................................................................ 105 Creating IAM users and Amazon SQS queues .............................................................................. 106 Testing attribute-based access control .......................................................................................... 110 Configuring queue parameters ............................................................................................................. 111 Configuring an access policy ................................................................................................................. 113 Configuring SSE-SQS for a queue ........................................................................................................ 113 v Amazon Simple Queue Service Developer Guide Configuring SSE-KMS for a queue ....................................................................................................... 115 Configuring tags for a queue ................................................................................................................ 116 Subscribing
sqs-dg-002
sqs-dg.pdf
2
for Java .................................................................................... 94 Using the Extended Client Library for Python ............................................................................. 100 Configuring Amazon SQS ............................................................................................................ 104 ABAC for Amazon SQS ........................................................................................................................... 104 What is ABAC? ..................................................................................................................................... 104 Why should I use ABAC in Amazon SQS? ...................................................................................... 105 Tagging for access control ................................................................................................................ 105 Creating IAM users and Amazon SQS queues .............................................................................. 106 Testing attribute-based access control .......................................................................................... 110 Configuring queue parameters ............................................................................................................. 111 Configuring an access policy ................................................................................................................. 113 Configuring SSE-SQS for a queue ........................................................................................................ 113 v Amazon Simple Queue Service Developer Guide Configuring SSE-KMS for a queue ....................................................................................................... 115 Configuring tags for a queue ................................................................................................................ 116 Subscribing a queue to a topic ............................................................................................................. 117 Cross-account subscriptions ............................................................................................................. 118 Cross-region subscriptions ................................................................................................................ 119 Configuring a Lambda trigger ............................................................................................................... 119 Prerequisites ........................................................................................................................................ 120 Automating notifications using EventBridge ..................................................................................... 121 Message attributes .................................................................................................................................. 121 Best practices ............................................................................................................................... 123 Error handling and problematic messages ......................................................................................... 123 Handling request errors in Amazon SQS ....................................................................................... 123 Capturing problematic messages in Amazon SQS ....................................................................... 124 Setting-up dead-letter queue retention in Amazon SQS ........................................................... 124 Message deduplication and grouping ................................................................................................. 124 Avoiding inconsistent message processing in Amazon SQS ...................................................... 125 Using the message deduplication ID .............................................................................................. 125 Using the message group ID ............................................................................................................ 127 Using the receive request attempt ID ............................................................................................ 129 Message processing and timing ............................................................................................................ 130 Processing messages in a timely manner in Amazon SQS ......................................................... 130 Setting-up long polling in Amazon SQS ....................................................................................... 131 Using the appropriate polling mode in Amazon SQS ................................................................. 132 Java SDK examples ...................................................................................................................... 133 Using server-side encryption ................................................................................................................. 133 Adding SSE to an existing queue .................................................................................................... 133 Disabling SSE for a queue ................................................................................................................ 134 Creating a queue with SSE ............................................................................................................... 135 Retrieving SSE attributes .................................................................................................................. 136 Configuring tags ....................................................................................................................................... 136 Listing tags ........................................................................................................................................... 136 Adding or updating tags ................................................................................................................... 137 Removing tags ..................................................................................................................................... 137 Sending message attributes .................................................................................................................. 138 Defining attributes ............................................................................................................................. 138 Sending a message with attributes ................................................................................................ 140 vi Amazon Simple Queue Service Developer Guide Using APIs .................................................................................................................................... 141 Making query API requests using AWS JSON protocol .................................................................... 142 Constructing an endpoint ................................................................................................................. 142 Making a POST request ..................................................................................................................... 143 Interpreting Amazon SQS JSON API responses ........................................................................... 144 Amazon SQS AWS JSON protocol FAQs ........................................................................................ 145 Making query API requests using AWS query protocol ................................................................... 148 Constructing an endpoint ................................................................................................................. 148 Making a GET request ....................................................................................................................... 149 Making a POST request ..................................................................................................................... 143 Interpreting Amazon SQS XML API responses ............................................................................. 151 Authenticating requests ......................................................................................................................... 152 Basic authentication process with HMAC-SHA ............................................................................. 153 Part 1: The request from the user .................................................................................................. 154 Part 2: The response from AWS ...................................................................................................... 155 Batch actions ............................................................................................................................................ 156 Batching message actions ................................................................................................................ 157 Enabling client-side buffering and request batching with Amazon SQS ................................. 158 Increasing throughput using horizontal scaling and action batching with Amazon SQS ..... 170 Working with AWS SDKs ........................................................................................................................ 182 Using JMS ..................................................................................................................................... 184 Prerequisites .............................................................................................................................................. 184 Using the Java Messaging Library ........................................................................................................ 185 Creating a JMS connection ............................................................................................................... 186 Creating an Amazon SQS queue ..................................................................................................... 186 Sending messages synchronously ................................................................................................... 187 Receiving messages synchronously ................................................................................................. 189 Receiving messages asynchronously .............................................................................................. 190 Using client acknowledge mode ..................................................................................................... 192 Using unordered acknowledge mode ............................................................................................. 193 Using the JMS Client with other Amazon SQS clients ..................................................................... 193 Working Java examples for using JMS with standard queues ........................................................ 195 ExampleConfiguration.java ............................................................................................................... 195 TextMessageSender.java .................................................................................................................... 198 SyncMessageReceiver.java ................................................................................................................. 199 AsyncMessageReceiver.java ............................................................................................................... 201 vii Amazon Simple Queue Service Developer Guide SyncMessageReceiverClientAcknowledge.java .............................................................................. 203 SyncMessageReceiverUnorderedAcknowledge.java ..................................................................... 207 SpringExampleConfiguration.xml .................................................................................................... 210 SpringExample.java ............................................................................................................................ 212 ExampleCommon.java ........................................................................................................................ 214 Supported JMS 1.1 implementations .................................................................................................. 216 Supported common interfaces ........................................................................................................ 216 Supported message types ................................................................................................................ 216 Supported message acknowledgment modes .............................................................................. 217 JMS-defined headers and reserved properties ............................................................................. 217 Tutorials ....................................................................................................................................... 219 Creating an Amazon SQS queue using AWS CloudFormation ........................................................ 219 Sending a message from a VPC ........................................................................................................... 221 Step 1: Create an Amazon EC2 key pair ........................................................................................ 222 Step 2: Create AWS resources ......................................................................................................... 222 Step 3: Confirm that your EC2 instance isn't publicly accessible .............................................. 223 Step 4: Create an Amazon VPC endpoint for Amazon SQS ....................................................... 224 Step 5: Send a message to your Amazon SQS queue ................................................................ 225 Code examples ............................................................................................................................. 227 Basics .......................................................................................................................................................... 240 Hello Amazon SQS ............................................................................................................................. 240 Actions .................................................................................................................................................. 252 Scenarios .................................................................................................................................................... 404 Create a messaging application ...................................................................................................... 404 Create a messenger application ...................................................................................................... 405 Create an Amazon Textract explorer application ......................................................................... 406 Create and publish to a FIFO topic ................................................................................................ 408 Detect people and objects in a video ............................................................................................ 420 Process S3 event notifications ......................................................................................................... 421 Publish messages to queues ............................................................................................................ 425 Send and receive batches of messages ......................................................................................... 540 Use the AWS Message Processing Framework for .NET with Amazon SQS ............................ 546 Use the Amazon SQS Java Messaging Library to work with the JMS interface ..................... 547 Work with queue tags ....................................................................................................................... 569 Serverless examples ................................................................................................................................ 572 Invoke a Lambda function from an Amazon SQS trigger ..........................................................
sqs-dg-003
sqs-dg.pdf
3
Create a messenger application ...................................................................................................... 405 Create an Amazon Textract explorer application ......................................................................... 406 Create and publish to a FIFO topic ................................................................................................ 408 Detect people and objects in a video ............................................................................................ 420 Process S3 event notifications ......................................................................................................... 421 Publish messages to queues ............................................................................................................ 425 Send and receive batches of messages ......................................................................................... 540 Use the AWS Message Processing Framework for .NET with Amazon SQS ............................ 546 Use the Amazon SQS Java Messaging Library to work with the JMS interface ..................... 547 Work with queue tags ....................................................................................................................... 569 Serverless examples ................................................................................................................................ 572 Invoke a Lambda function from an Amazon SQS trigger .......................................................... 572 viii Amazon Simple Queue Service Developer Guide Reporting batch item failures for Lambda functions with an Amazon SQS trigger .............. 581 Troubleshooting ........................................................................................................................... 592 Access denied error ................................................................................................................................. 592 Amazon SQS queue policy and IAM policy ................................................................................... 593 AWS Key Management Service (AWS KMS) permissions ............................................................ 593 VPC endpoint policy .......................................................................................................................... 595 Organization service control policy ................................................................................................ 595 API errors ................................................................................................................................................... 596 QueueDoesNotExist error ................................................................................................................. 596 InvalidAttributeValue error ............................................................................................................... 596 ReceiptHandle error ........................................................................................................................... 597 DLQ and DLQ redrive issues .................................................................................................................. 598 DLQ issues ............................................................................................................................................ 598 DLQ-redrive issues .............................................................................................................................. 599 FIFO throttling issues .............................................................................................................................. 601 Messages not returned for a ReceiveMessage API call .................................................................... 602 Empty queue ....................................................................................................................................... 602 In flight limit reached ........................................................................................................................ 602 Message delay ..................................................................................................................................... 602 Message is in flight ............................................................................................................................ 603 Polling method ................................................................................................................................... 603 Network errors .......................................................................................................................................... 603 ETIMEOUT error .................................................................................................................................. 603 UnknownHostException error .......................................................................................................... 605 Troubleshooting queues using X-Ray .................................................................................................. 605 Security ........................................................................................................................................ 607 Data protection ........................................................................................................................................ 607 Data encryption .................................................................................................................................. 608 Internetwork traffic privacy .............................................................................................................. 619 Identity and access management ......................................................................................................... 621 Audience ............................................................................................................................................... 621 Authenticating with identities ......................................................................................................... 622 Managing access using policies ....................................................................................................... 625 Overview ............................................................................................................................................... 628 How Amazon Simple Queue Service works with IAM ................................................................. 635 AWS managed policies ...................................................................................................................... 642 ix Amazon Simple Queue Service Developer Guide Troubleshooting .................................................................................................................................. 644 Using policies ....................................................................................................................................... 646 Logging and monitoring ........................................................................................................................ 691 Logging API calls ................................................................................................................................ 694 Monitoring queues ............................................................................................................................. 698 Compliance validation ............................................................................................................................ 712 Resilience ................................................................................................................................................... 713 Distributed queues ............................................................................................................................. 713 Infrastructure security ............................................................................................................................. 714 Best practices ............................................................................................................................................ 714 Make sure that queues aren't publicly accessible ........................................................................ 714 Implement least-privilege access .................................................................................................... 715 Use IAM roles for applications and AWS services which require Amazon SQS access ........... 715 Implement server-side encryption .................................................................................................. 716 Enforce encryption of data in transit ............................................................................................. 716 Consider using VPC endpoints to access Amazon SQS ............................................................... 716 Related resources ........................................................................................................................ 717 Documentation history ............................................................................................................... 718 x Amazon Simple Queue Service Developer Guide What is Amazon Simple Queue Service? Amazon Simple Queue Service (Amazon SQS) offers a secure, durable, and available hosted queue that lets you integrate and decouple distributed software systems and components. Amazon SQS offers common constructs such as dead-letter queues and cost allocation tags. It provides a generic web services API that you can access using any programming language that the AWS SDK supports. Benefits of using Amazon SQS • Security – You control who can send messages to and receive messages from an Amazon SQS queue. You can choose to transmit sensitive data by protecting the contents of messages in queues by using default Amazon SQS managed server-side encryption (SSE), or by using custom SSE keys managed in AWS Key Management Service (AWS KMS). • Durability – For the safety of your messages, Amazon SQS stores them on multiple servers. Standard queues support at-least-once message delivery, and FIFO queues support exactly-once message processing and high-throughput mode. • Availability – Amazon SQS uses redundant infrastructure to provide highly-concurrent access to messages and high availability for producing and consuming messages. • Scalability – Amazon SQS can process each buffered request independently, scaling transparently to handle any load increases or spikes without any provisioning instructions. • Reliability – Amazon SQS locks your messages during processing, so that multiple producers can send and multiple consumers can receive messages at the same time. • Customization – Your queues don't have to be exactly alike—for example, you can set a default delay on a queue. You can store the contents of messages larger than 256 KB using Amazon Simple Storage Service (Amazon S3) or Amazon DynamoDB, with Amazon SQS holding a pointer to the Amazon S3 object, or you can split a large message into smaller messages. Basic Amazon SQS architecture This section describes the components of a distributed messaging system and explains the lifecycle of an Amazon SQS message. Benefits of using Amazon SQS 1 Amazon Simple Queue Service Distributed queues Developer Guide There are three main parts in a distributed messaging system: the components of your distributed system, your queue (distributed on Amazon SQS servers), and the messages in the queue. In the following scenario, your system has several producers (components that send messages to the queue) and consumers (components that receive messages from the queue). The queue
sqs-dg-004
sqs-dg.pdf
4
split a large message into smaller messages. Basic Amazon SQS architecture This section describes the components of a distributed messaging system and explains the lifecycle of an Amazon SQS message. Benefits of using Amazon SQS 1 Amazon Simple Queue Service Distributed queues Developer Guide There are three main parts in a distributed messaging system: the components of your distributed system, your queue (distributed on Amazon SQS servers), and the messages in the queue. In the following scenario, your system has several producers (components that send messages to the queue) and consumers (components that receive messages from the queue). The queue (which holds messages A through E) redundantly stores the messages across multiple Amazon SQS servers. Message lifecycle The following scenario describes the lifecycle of an Amazon SQS message in a queue, from creation to deletion. Distributed queues 2 Amazon Simple Queue Service Developer Guide A producer (Component 1) sends message A to a queue, and the message is distributed across the Amazon SQS servers redundantly. When a consumer (Component 2) is ready to process messages, it consumes messages from the queue, and message A is returned. While message A is being processed, it remains in the queue and isn't returned to subsequent receive requests for the duration of the visibility timeout. Message lifecycle 3 Amazon Simple Queue Service Developer Guide The consumer (Component 2) deletes message A from the queue to prevent the message from being received and processed again when the visibility timeout expires. Note Amazon SQS automatically deletes messages that have been in a queue for more than the maximum message retention period. The default message retention period is 4 days. However, you can set the message retention period to a value from 60 seconds to 1,209,600 seconds (14 days) using the SetQueueAttributes action. Differences between Amazon SQS, Amazon MQ, and Amazon SNS Amazon SQS, Amazon SNS, and Amazon MQ offer highly scalable and easy-to-use managed messaging services, each designed for specific roles within distributed systems. Here's an enhanced overview of the differences between these services: Amazon SQS decouples and scales distributed software systems and components as a queue service. It processes messages through a single subscriber typically, ideal for workflows where order and loss prevention are critical. For wider distribution, integrating Amazon SQS with Amazon SNS enables a fanout messaging pattern, effectively pushing messages to multiple subscribers at once. Amazon SNS allows publishers to send messages to multiple subscribers through topics, which serve as communication channels. Subscribers receive published messages using a supported endpoint type, such as Amazon Data Firehose, Amazon SQS, Lambda, HTTP, email, mobile push notifications, and mobile text messages (SMS). This service is ideal for scenarios requiring immediate notifications, such as real-time user engagement or alarm systems. To prevent message loss when subscribers are offline, integrating Amazon SNS with Amazon SQS queue messages ensures consistent delivery. Amazon MQ fits best with enterprises looking to migrate from traditional message brokers, supporting standard messaging protocols like AMQP and MQTT, along with Apache ActiveMQ and RabbitMQ. It offers compatibility with legacy systems needing stable, reliable messaging without significant reconfiguration. The following chart provides an overview of each services' resource type: Differences between Amazon SQS, Amazon MQ, and Amazon SNS 4 Amazon Simple Queue Service Developer Guide Resource type Amazon SNS Amazon SQS Amazon MQ Synchronous Asynchronous Queues Publisher-subscriber messaging No Yes No Yes Message brokers No No Yes Yes No No Yes Yes Yes Yes Yes Both Amazon SQS and Amazon SNS are recommended for new applications that can benefit from nearly unlimited scalability and simple APIs. They generally offer more cost-effective solutions for high-volume applications with their pay-as-you-go pricing. We recommend Amazon MQ for migrating applications from existing message brokers that rely on compatibility with APIs such as JMS or protocols such as Advanced Message Queuing Protocol (AMQP), MQTT, OpenWire, and Simple Text Oriented Message Protocol (STOMP). Differences between Amazon SQS, Amazon MQ, and Amazon SNS 5 Amazon Simple Queue Service Developer Guide Getting started with Amazon SQS This topic guides you through using the Amazon SQS console to create and manage standard queues and FIFO queues. You'll learn how to navigate the console, view queue attributes, and distinguish between queue types. Key tasks include sending, receiving, and configuring messages, adjusting parameters such as visibility timeout and message retention, and managing queue access through policies. Topics • Setting up Amazon SQS • Understanding the Amazon SQS console • Amazon SQS queue types • Creating an Amazon SQS standard queue and sending a message • Creating an Amazon SQS FIFO queue and sending a message • Common tasks for getting started with Amazon SQS Setting up Amazon SQS Before you can use Amazon SQS for the first time, you must complete the following steps: Step 1: Create an AWS account and IAM user To access any AWS
sqs-dg-005
sqs-dg.pdf
5
receiving, and configuring messages, adjusting parameters such as visibility timeout and message retention, and managing queue access through policies. Topics • Setting up Amazon SQS • Understanding the Amazon SQS console • Amazon SQS queue types • Creating an Amazon SQS standard queue and sending a message • Creating an Amazon SQS FIFO queue and sending a message • Common tasks for getting started with Amazon SQS Setting up Amazon SQS Before you can use Amazon SQS for the first time, you must complete the following steps: Step 1: Create an AWS account and IAM user To access any AWS service, you first need to create an AWS account, an Amazon.com account that can use AWS products. You can use your AWS account to view your activity and usage reports and to manage authentication and access. To avoid using your AWS account root user for Amazon SQS actions, it is a best practice to create an IAM user for each person who needs administrative access to Amazon SQS. Sign up for an AWS account If you do not have an AWS account, complete the following steps to create one. To sign up for an AWS account 1. Open https://portal.aws.amazon.com/billing/signup. Setting up 6 Amazon Simple Queue Service Developer Guide 2. Follow the online instructions. Part of the sign-up procedure involves receiving a phone call and entering a verification code on the phone keypad. When you sign up for an AWS account, an AWS account root user is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to perform tasks that require root user access. AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to https://aws.amazon.com/ and choosing My Account. Create a user with administrative access After you sign up for an AWS account, secure your AWS account root user, enable AWS IAM Identity Center, and create an administrative user so that you don't use the root user for everyday tasks. Secure your AWS account root user 1. Sign in to the AWS Management Console as the account owner by choosing Root user and entering your AWS account email address. On the next page, enter your password. For help signing in by using root user, see Signing in as the root user in the AWS Sign-In User Guide. 2. Turn on multi-factor authentication (MFA) for your root user. For instructions, see Enable a virtual MFA device for your AWS account root user (console) in the IAM User Guide. Create a user with administrative access 1. Enable IAM Identity Center. For instructions, see Enabling AWS IAM Identity Center in the AWS IAM Identity Center User Guide. 2. In IAM Identity Center, grant administrative access to a user. Step 1: Create an AWS account and IAM user 7 Amazon Simple Queue Service Developer Guide For a tutorial about using the IAM Identity Center directory as your identity source, see Configure user access with the default IAM Identity Center directory in the AWS IAM Identity Center User Guide. Sign in as the user with administrative access • To sign in with your IAM Identity Center user, use the sign-in URL that was sent to your email address when you created the IAM Identity Center user. For help signing in using an IAM Identity Center user, see Signing in to the AWS access portal in the AWS Sign-In User Guide. Assign access to additional users 1. In IAM Identity Center, create a permission set that follows the best practice of applying least- privilege permissions. For instructions, see Create a permission set in the AWS IAM Identity Center User Guide. 2. Assign users to a group, and then assign single sign-on access to the group. For instructions, see Add groups in the AWS IAM Identity Center User Guide. Step 2: Grant programmatic access To use Amazon SQS actions (for example, using Java or through the AWS Command Line Interface), you need an access key ID and a secret access key. Note The access key ID and secret access key are specific to AWS Identity and Access Management. Don't confuse them with credentials for other AWS services, such as Amazon EC2 key pairs. Users need programmatic access if they want to interact with AWS outside of the AWS Management Console. The way to grant programmatic access depends on the type of user that's accessing AWS. Step 2: Grant programmatic access 8 Amazon Simple Queue Service Developer Guide To grant users programmatic access, choose one of the following options. Which user needs programmatic access? To By Workforce identity (Users managed in IAM Identity Center) Use temporary credentials
sqs-dg-006
sqs-dg.pdf
6
and secret access key are specific to AWS Identity and Access Management. Don't confuse them with credentials for other AWS services, such as Amazon EC2 key pairs. Users need programmatic access if they want to interact with AWS outside of the AWS Management Console. The way to grant programmatic access depends on the type of user that's accessing AWS. Step 2: Grant programmatic access 8 Amazon Simple Queue Service Developer Guide To grant users programmatic access, choose one of the following options. Which user needs programmatic access? To By Workforce identity (Users managed in IAM Identity Center) Use temporary credentials to sign programmatic requests Following the instructions for the interface that you want to to the AWS CLI, AWS SDKs, or use. AWS APIs. • For the AWS CLI, see Configuring the AWS CLI to use AWS IAM Identity Center in the AWS Command Line Interface User Guide. • For AWS SDKs, tools, and AWS APIs, see IAM Identity Center authentication in the AWS SDKs and Tools Reference Guide. IAM IAM Use temporary credentials to sign programmatic requests Following the instructions in Using temporary credentia to the AWS CLI, AWS SDKs, or ls with AWS resources in the AWS APIs. IAM User Guide. (Not recommended) Use long-term credentials to Following the instructions for the interface that you want to sign programmatic requests to the AWS CLI, AWS SDKs, or AWS APIs. use. • For the AWS CLI, see Authenticating using IAM user credentials in the AWS Command Line Interface User Guide. • For AWS SDKs and tools, see Authenticate using long-term credentials in Step 2: Grant programmatic access 9 Amazon Simple Queue Service Developer Guide Which user needs programmatic access? To By the AWS SDKs and Tools Reference Guide. • For AWS APIs, see Managing access keys for IAM users in the IAM User Guide. Step 3: Get ready to use the example code This guide includes examples that use the AWS SDK for Java. To run the example code, follow the set-up instructions in Getting Started with AWS SDK for Java 2.0. You can develop AWS applications in other programming languages, such as Go, JavaScript, Python and Ruby. For more information, see Tools to Build on AWS. Note You can explore Amazon SQS without writing code with tools such as the AWS Command Line Interface (AWS CLI) or Windows PowerShell. You can find AWS CLI examples in the Amazon SQS section of the AWS CLI Command Reference. You can find Windows PowerShell examples in the Amazon Simple Queue Service section of the AWS Tools for PowerShell Cmdlet Reference. Next steps You are now ready for Getting started with managing Amazon SQS queues and messages using the AWS Management Console. Understanding the Amazon SQS console When you open the Amazon SQS console, choose Queues from the navigation pane. The Queues page provides information about all of your queues in the active region. Step 3: Get ready to use the example code 10 Amazon Simple Queue Service Developer Guide Each queue entry provides essential information about the queue, including its type and key attributes. Standard queues, optimized for maximum throughput and best-effort message ordering, are distinguished from First-In-First-Out (FIFO) queues, which prioritize message ordering and uniqueness for applications requiring strict message sequencing. Interactive elements and actions From the Queues page, you have multiple options for managing your queues: 1. Quick Actions – Adjacent to each queue name, a dropdown menu offers quick access to common actions such as sending messages, viewing or deleting messages, configuring triggers, and deleting the queue itself. 2. Detailed View and Configuration – Clicking on a queue name opens its Details page, where you can delve deeper into queue settings and configurations. Here, you can adjust parameters like message retention period, visibility timeout, and maximum message size to tailor the queue to your application's requirements. Region selection and resource tags Understanding the Amazon SQS console 11 Amazon Simple Queue Service Developer Guide Ensure you're in the correct AWS Region to access and manage your queues effectively. Additionally, consider utilizing resource tags to organize and categorize your queues, enabling better resource management, cost allocation, and access control within your AWS shared environment. By leveraging the features and functionalities offered within the Amazon SQS console, you can efficiently manage your messaging infrastructure, optimize queue performance, and ensure reliable message delivery for your applications. Amazon SQS queue types Amazon SQS supports two types of queues: standard queues and FIFO queues. Use the following table to determine which queue best fits your needs. Standard queues FIFO queues Unlimited throughput – Standard queues support a very high, nearly unlimited High throughput – When you use batching, FIFO queues process up to 3,000 messages number of API calls per second, per action (SendMessage , ReceiveMessage , or DeleteMessage ). This high throughput makes
sqs-dg-007
sqs-dg.pdf
7
offered within the Amazon SQS console, you can efficiently manage your messaging infrastructure, optimize queue performance, and ensure reliable message delivery for your applications. Amazon SQS queue types Amazon SQS supports two types of queues: standard queues and FIFO queues. Use the following table to determine which queue best fits your needs. Standard queues FIFO queues Unlimited throughput – Standard queues support a very high, nearly unlimited High throughput – When you use batching, FIFO queues process up to 3,000 messages number of API calls per second, per action (SendMessage , ReceiveMessage , or DeleteMessage ). This high throughput makes them ideal for use cases that require per second per API method (SendMessa geBatch , ReceiveMessage , or DeleteMessageBatch relies on 300 API calls per second, with each ). This throughput processing large volumes of messages quickly, API call handling a batch of 10 messages. such as real-time data streaming or large-sca By enabling high throughput mode, you can le applications. While standard queues scale scale up to 30,000 transactions per second automatically with demand, it is essential to (TPS) with relaxed ordering within message monitor usage patterns to ensure optimal groups. Without batching, FIFO queues performance, especially in regions with higher support up to 300 API calls per second per workloads. At-least-once delivery – Guaranteed at-least- once delivery, meaning that every message is delivered at least once, but in some cases, a message may be delivered more than once due to retries or network delays. You should design your application to handle potential duplicate messages by using idempotent operations, which ensure that processing the API method (SendMessage , ReceiveMe ssage , or DeleteMessage ). If you need more throughput, you can request a quota increase through the AWS Support Center. To enable high-throughput mode, see Enabling high throughput for FIFO queues in Amazon SQS. Exactly-once processing – FIFO queues deliver each message once and keep it available Queue types 12 Amazon Simple Queue Service Developer Guide Standard queues FIFO queues same message multiple times will not affect until you process and delete it. By using the system’s state. Best-effort ordering – Provides best-effort ordering, meaning that while Amazon SQS attempts to deliver messages in the order features like MessageDeduplicationId or content-based deduplication, you prevent duplicate messages, even when retrying due to network issues or timeouts. they were sent, it does not guarantee this. In some cases, messages may arrive out of order, First-in-first-out delivery – FIFO queues ensure that you receive messages in the order especially under conditions of high throughpu they are sent within each message group. By t or failure recovery. For applications where distributing messages across multiple groups, the order of message processing is crucial, you can process them in parallel while still you should handle reordering logic within maintaining the order within each group. the application or use FIFO queues for strict ordering guarantees. Durability and redundancy – Standard queues ensure high durability by storing multiple copies of each message across multiple AWS Availability Zones. This ensures that messages are not lost, even in the event of infrastructure failures. Visibility timeout – Amazon SQS allows you to configure a visibility timeout to control how long a message stays hidden after being received, ensuring that other consumers do not process the message until it has been fully handled or the timeout expires. Queue types 13 Amazon Simple Queue Service Developer Guide Standard queues FIFO queues Use standard queues to send data between applications when throughput is crucial, for Use FIFO queues to send data between applications when the order of events is example: important, for example: • Decouple live user requests from intensive background work. Allow users to upload media quickly while you process tasks • Make sure that user-entered commands are run in the right order. This is a key use case for FIFO queues, where command order like resizing or encoding in the backgroun is crucial. For example, if a user performs a d, ensuring fast response times without sequence of actions in an application, FIFO overloading the system. queues ensure the actions are processed in • Allocate tasks to multiple worker nodes. Distribute a high number of credit card the same order they were entered. • Display the correct product price by validation requests across multiple worker nodes, and handle duplicate messages with idempotent operations to avoid processing sending price modifications in the right order. FIFO queues ensure that multiple updates to a product's price arrive and are errors. • Batch messages for future processing. Queue multiple entries for batch additions to a database. Since message order isn’t processed sequentially. Without FIFO, a price reduction might be processed after a price increase, causing incorrect data to be displayed. guaranteed, design your system to handle • Prevent a student from enrolling in a out-of-order
sqs-dg-008
sqs-dg.pdf
8
were entered. • Display the correct product price by validation requests across multiple worker nodes, and handle duplicate messages with idempotent operations to avoid processing sending price modifications in the right order. FIFO queues ensure that multiple updates to a product's price arrive and are errors. • Batch messages for future processing. Queue multiple entries for batch additions to a database. Since message order isn’t processed sequentially. Without FIFO, a price reduction might be processed after a price increase, causing incorrect data to be displayed. guaranteed, design your system to handle • Prevent a student from enrolling in a out-of-order processing if necessary. course before registering for an account. By using FIFO queues, you ensure that the registration process occurs in the correct sequence. The system processes the account registration first and then the course enrollment, preventing the enrollment request from being executed prematurely. Implementing request-response systems in Amazon SQS When implementing a request-response or remote procedure call (RPC) system, keep the following best practices in mind: Implementing request-response systems in Amazon SQS 14 Amazon Simple Queue Service Developer Guide • Create reply queues on start-up – Instead of creating reply queues per message, create them on start-up, per producer. Use a correlation ID message attribute to map replies to requests efficiently. • Avoid sharing reply queues among producers – Ensure that each producer has its own reply queue. Sharing reply queues can result in a producer receiving response messages intended for another producer. For more information about implementing the request-response pattern using the Temporary Queue Client, see Request-response messaging pattern (virtual queues). Creating an Amazon SQS standard queue and sending a message You can create a standard queue and send messages using the Amazon SQS console. This topic also emphasizes best practices, including avoiding sensitive information in queue names and utilizing managed server-side encryption. Creating a standard queue using the Amazon SQS console Important On August 17, 2022, default server-side encryption (SSE) was applied to all Amazon SQS queues. Do not add personally identifiable information (PII) or other confidential or sensitive information in queue names. Queue names are accessible to many Amazon Web Services, including billing and CloudWatch logs. Queue names are not intended to be used for private or sensitive data. To create an Amazon SQS standard queue 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. Choose Create queue. 3. For Type, the Standard queue type is set by default. Creating a standard queue 15 Amazon Simple Queue Service Developer Guide Note You can't change the queue type after you create the queue. 4. 5. Enter a Name for your queue. (Optional) The console sets default values for the queue configuration parameters. Under Configuration, you can set new values for the following parameters: a. b. c. d. e. For Visibility timeout , enter the duration and units. The range is from 0 seconds to 12 hours. The default value is 30 seconds. For Message retention period, enter the duration and units. The range is from 1 minute to 14 days. The default value is 4 days. For Delivery delay, enter the duration and units. The range is from 0 seconds to 15 minutes. The default value is 0 seconds. For Maximum message size, enter a value. The range is from 1 KB to 256 KB. The default value is 256 KB. For Receive message wait time, enter a value. The range is from 0 to 20 seconds. The default value is 0 seconds, which sets short polling. Any non-zero value sets long polling. 6. (Optional) Define an Access policy. The access policy defines the accounts, users, and roles that can access the queue. The access policy also defines the actions (such as SendMessage, ReceiveMessage, or DeleteMessage) that the users can access. The default policy allows only the queue owner to send and receive messages. To define the access policy, do one of the following: • Choose Basic to configure who can send messages to the queue and who can receive messages from the queue. The console creates the policy based on your choices and displays the resulting access policy in the read-only JSON panel. • Choose Advanced to modify the JSON access policy directly. This allows you to specify a custom set of actions that each principal (account, user, or role) can perform. 7. For Redrive allow policy, choose Enabled. Select one of the following: Allow all, By queue, or Deny all. When choosing By queue, specify a list of up to 10 source queues by the Amazon Resource Name (ARN). 8. Amazon SQS provides managed server-side encryption by default. To choose an encryption key type, or to disable Amazon SQS managed server-side encryption, expand Encryption. Creating a queue 16 Amazon Simple Queue Service Developer Guide For more on encryption key types, see Configuring server-side encryption for
sqs-dg-009
sqs-dg.pdf
9
to specify a custom set of actions that each principal (account, user, or role) can perform. 7. For Redrive allow policy, choose Enabled. Select one of the following: Allow all, By queue, or Deny all. When choosing By queue, specify a list of up to 10 source queues by the Amazon Resource Name (ARN). 8. Amazon SQS provides managed server-side encryption by default. To choose an encryption key type, or to disable Amazon SQS managed server-side encryption, expand Encryption. Creating a queue 16 Amazon Simple Queue Service Developer Guide For more on encryption key types, see Configuring server-side encryption for a queue using SQS-managed encryption keys and Configuring server-side encryption for a queue using the Amazon SQS console. Note With SSE enabled, anonymous SendMessage and ReceiveMessage requests to the encrypted queue will be rejected. Amazon SQS security best practises recommend against using anonymous requests. If you wish to send anonymous requests to an Amazon SQS queue, make sure to disable SSE. 9. (Optional) To configure a dead-letter queue to receive undeliverable messages, expand Dead- letter queue. 10. (Optional) To add tags to the queue, expand Tags. 11. Choose Create queue. Amazon SQS creates the queue and displays the queue's Details page. Amazon SQS propagates information about the new queue across the system. Because Amazon SQS is a distributed system, you might experience a slight delay before the console displays the queue on the Queues page. Sending a message using a standard queue After your queue has been created, you can send a message to it. 1. From the left navigation pane, choose Queues. From the queue list, select the queue that you created. 2. From Actions, choose Send and receive messages. 3. 4. The console displays the Send and receive messages page. In the Message body, enter the message text. For a standard queue, you can enter a value for Delivery delay and choose the units. For example, enter 60 and choose seconds. For more information, see Amazon SQS message timers. 5. Choose Send message. When your message is sent, the console displays a success message. Choose View details to display information about the sent message. Sending a message using a standard queue 17 Amazon Simple Queue Service Developer Guide Creating an Amazon SQS FIFO queue and sending a message You can create an Amazon SQS FIFO queue and send messages using the console. This topic explains how to set up queue parameters, including visibility timeout, message retention, and deduplication, while following security best practices such as avoiding sensitive information in queue names and enabling server-side encryption. It also covers defining access policies, configuring dead-letter queues, and sending messages with FIFO-specific attributes like message group ID and deduplication ID. Creating a FIFO queue using the Amazon SQS console You can use the Amazon SQS console to create FIFO queues. The console provides default values for all settings except for the queue name. Important On August 17, 2022, default server-side encryption (SSE) was applied to all Amazon SQS queues. Do not add personally identifiable information (PII) or other confidential or sensitive information in queue names. Queue names are accessible to many Amazon Web Services, including billing and CloudWatch logs. Queue names are not intended to be used for private or sensitive data. To create an Amazon SQS FIFO queue 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. Choose Create queue. 3. For Type, the Standard queue type is set by default. To create a FIFO queue, choose FIFO. Note You can't change the queue type after you create the queue. 4. Enter a Name for your queue. Creating a FIFO queue 18 Amazon Simple Queue Service Developer Guide The name of a FIFO queue must end with the .fifo suffix. The suffix counts towards the 80- character queue name quota. To determine whether a queue is FIFO, you can check whether the queue name ends with the suffix. 5. (Optional) The console sets default values for the queue configuration parameters. Under Configuration, you can set new values for the following parameters: a. b. c. d. e. f. g. For Visibility timeout , enter the duration and units. The range is from 0 seconds to 12 hours. The default value is 30 seconds. For Message retention period, enter the duration and units. The range is from 1 minute to 14 days. The default value is 4 days. For Delivery delay, enter the duration and units. The range is from 0 seconds to 15 minutes. The default value is 0 seconds. For Maximum message size, enter a value. The range is from 1 KB to 256 KB. The default value is 256 KB. For Receive message wait time, enter a value. The range is from 0 to 20 seconds. The default value is 0 seconds, which sets short polling. Any non-zero value
sqs-dg-010
sqs-dg.pdf
10
30 seconds. For Message retention period, enter the duration and units. The range is from 1 minute to 14 days. The default value is 4 days. For Delivery delay, enter the duration and units. The range is from 0 seconds to 15 minutes. The default value is 0 seconds. For Maximum message size, enter a value. The range is from 1 KB to 256 KB. The default value is 256 KB. For Receive message wait time, enter a value. The range is from 0 to 20 seconds. The default value is 0 seconds, which sets short polling. Any non-zero value sets long polling. For a FIFO queue, choose Content-based deduplication to enable content-based deduplication. The default setting is disabled. (Optional) For a FIFO queue to enable higher throughput for sending and receiving messages in the queue, choose Enable high throughput FIFO. Choosing this option changes the related options (Deduplication scope and FIFO throughput limit) to the required settings for enabling high throughput for FIFO queues. If you change any of the settings required for using high throughput FIFO, normal throughput is in effect for the queue, and deduplication occurs as specified. For more information, see High throughput for FIFO queues in Amazon SQS and Amazon SQS message quotas. 6. (Optional) Define an Access policy. The access policy defines the accounts, users, and roles that can access the queue. The access policy also defines the actions (such as SendMessage, ReceiveMessage, or DeleteMessage) that the users can access. The default policy allows only the queue owner to send and receive messages. To define the access policy, do one of the following: Create a queue 19 Amazon Simple Queue Service Developer Guide • Choose Basic to configure who can send messages to the queue and who can receive messages from the queue. The console creates the policy based on your choices and displays the resulting access policy in the read-only JSON panel. • Choose Advanced to modify the JSON access policy directly. This allows you to specify a custom set of actions that each principal (account, user, or role) can perform. 7. For Redrive allow policy, choose Enabled. Select one of the following: Allow all, By queue, or Deny all. When choosing By queue, specify a list of up to 10 source queues by the Amazon Resource Name (ARN). 8. Amazon SQS provides managed server-side encryption by default. To choose an encryption key type, or to disable Amazon SQS managed server-side encryption, expand Encryption. For more on encryption key types, see Configuring server-side encryption for a queue using SQS-managed encryption keys and Configuring server-side encryption for a queue using the Amazon SQS console. Note With SSE enabled, anonymous SendMessage and ReceiveMessage requests to the encrypted queue will be rejected. Amazon SQS security best practises recommend against using anonymous requests. If you wish to send anonymous requests to an Amazon SQS queue, make sure to disable SSE. 9. (Optional) To configure a dead-letter queue to receive undeliverable messages, expand Dead- letter queue. 10. (Optional) To add tags to the queue, expand Tags. 11. Choose Create queue. Amazon SQS creates the queue and displays the queue's Details page. Amazon SQS propagates information about the new queue across the system. Because Amazon SQS is a distributed system, you might experience a slight delay before the console displays the queue on the Queues page. After creating a queue, you can send messages to it, and receive and delete messages. You can also edit any of the queue configuration settings except the queue type. Sending a message using a FIFO queue After you create your queue, you can send a message to it. Sending a message using a FIFO queue 20 Amazon Simple Queue Service Developer Guide 1. From the left navigation pane, choose Queues. From the queue list, select the queue that you created. 2. From Actions, choose Send and receive messages. 3. 4. 5. The console displays the Send and receive messages page. In the Message body, enter the message text. For a First-In-First-Out (FIFO) queue, enter a Message group ID. For more information, see FIFO queue delivery logic in Amazon SQS. (Optional) For a FIFO queue, you can enter a Message deduplication ID. If you enabled content-based deduplication for the queue, the message deduplication ID isn't required. For more information, see FIFO queue delivery logic in Amazon SQS. 6. FIFO queues does not support timers on individual messages. For more information, see Amazon SQS message timers. 7. Choose Send message. When your message is sent, the console displays a success message. Choose View details to display information about the sent message. Common tasks for getting started with Amazon SQS Once you've created a queue and learned how to send, receive, and delete messages, you might want to try the following: • Trigger a Lambda function
sqs-dg-011
sqs-dg.pdf
11
enabled content-based deduplication for the queue, the message deduplication ID isn't required. For more information, see FIFO queue delivery logic in Amazon SQS. 6. FIFO queues does not support timers on individual messages. For more information, see Amazon SQS message timers. 7. Choose Send message. When your message is sent, the console displays a success message. Choose View details to display information about the sent message. Common tasks for getting started with Amazon SQS Once you've created a queue and learned how to send, receive, and delete messages, you might want to try the following: • Trigger a Lambda function to process incoming messages automatically, enabling event-driven workflows without the need for continuous polling. • Configure queues, including SSE and other features. • Send a message with attributes. • Send a message from a VPC. • Discover the functionality and architecture of Amazon SQS. • Discover guidelines and caveats that will help you make the most of Amazon SQS. • Explore the Amazon SQS examples for an AWS SDK, such as the AWS SDK for Java 2.x Developer Guide. • Learn about Amazon SQS AWS CLI commands. • Learn about Amazon SQS API actions. Common tasks 21 Amazon Simple Queue Service Developer Guide • Learn how to interact with Amazon SQS programmatically. See Working with APIs and explore the AWS Development Center: • Java • JavaScript • PHP • Python • Ruby • Windows & .NET • Learn how to monitor costs and resources. • Learn how to protect your data. • Learn more about the Amazon SQS workflow. Common tasks 22 Amazon Simple Queue Service Developer Guide Managing an Amazon SQS queue Learn how to manage Amazon SQS queues using the console, including editing queue settings, receiving and deleting messages, confirming queue emptiness, and deleting or purging queues. Understand best practices for efficient message handling, such as using long polling, managing visibility timeouts, and verifying metrics through monitoring dashboards or the AWS CLI. Follow practical steps to maintain queues and handle messages effectively while minimizing disruptions. Editing an Amazon SQS queue using the console You can use the Amazon SQS console to edit queue configuration parameters (except the queue type) and modify or remove features as needed. To edit an Amazon SQS queue (console) 1. Open the Queues page of the Amazon SQS console. 2. 3. 4. 5. 6. 7. Select a queue, and then choose Edit. (Optional) Under Configuration, update the queue's configuration parameters. (Optional) To update the access policy, under Access policy, modify the JSON policy. (Optional) To update a dead-letter queue redrive allow policy, expand Redrive allow policy. (Optional) To update or remove encryption, expand Encryption. (Optional) To add, update, or remove a dead-letter queue (which allows you to receive undeliverable messages), expand Dead-letter queue. 8. (Optional) To add, update, or remove the tags for the queue, expand Tags. 9. Choose Save. • The console displays the Details page for the queue. Receiving and deleting a message in Amazon SQS After sending messages to an Amazon SQS queue, you can retrieve and delete them to process your application workflow. This process ensures secure and reliable message handling. This topic walks you through retrieving and deleting messages using the Amazon SQS console and explains key settings to optimize this operation. The following are key concepts for receiving and deleting messages: Editing a queue 23 Amazon Simple Queue Service 1. Receiving messages Developer Guide • When you retrieve messages from an Amazon SQS queue, you cannot target specific messages. Instead, specify the maximum number of messages to retrieve in a single request (up to 10). • Due to Amazon SQS's distributed nature, retrieving from a queue with few messages may return an empty response. To mitigate this: • Use long polling, which waits until a message is available or the poll times out. This approach reduces unnecessary polling costs and improves efficiency. • Re-issue the request if needed. 2. Message visibility and deletion • Messages are not deleted automatically after retrieval. This feature ensures you can reprocess messages in case of application failures or network disruptions. • After processing, you must explicitly send a delete request to remove the message permanently. This action confirms successful handling. • Messages retrieved using the Amazon SQS console remain visible for re-retrieval. Adjust the visibility timeout setting for automated environments to temporarily hide messages from other consumers while they are being processed. 3. Visibility timeout • This setting determines how long a message remains hidden after retrieval. Set an appropriate timeout to ensure messages are processed only once and to prevent duplication during distributed processing. To receive and delete a message using the console 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. On the Queues page, choose the queue you want to receive messages
sqs-dg-012
sqs-dg.pdf
12
retrieved using the Amazon SQS console remain visible for re-retrieval. Adjust the visibility timeout setting for automated environments to temporarily hide messages from other consumers while they are being processed. 3. Visibility timeout • This setting determines how long a message remains hidden after retrieval. Set an appropriate timeout to ensure messages are processed only once and to prevent duplication during distributed processing. To receive and delete a message using the console 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. On the Queues page, choose the queue you want to receive messages from, and then select Send and receive messages. 4. On the Send and receive messages page, select Poll for messages. Amazon SQS displays a progress bar indicating the polling duration. Messages retrieved will appear in the Messages section, showing: • Message ID Receiving and deleting a message 24 Amazon Simple Queue Service • Sent date • Size • Receive count Developer Guide 5. To delete messages, choose the ones you want to remove and select Delete. Confirm deletion in the Delete Messages dialog box by selecting Delete. For more details on advanced operations, including API-based message retrieval and deletion, see the Amazon SQS API Reference Guide. Confirming that an Amazon SQS queue is empty In most cases, you can use long polling to determine if a queue is empty. In rare cases, you might receive empty responses even when a queue still contains messages, especially if you specified a low value for Receive message wait time when you created the queue. This section describes how to confirm that a queue is empty. To confirm that a queue is empty (console) 1. Stop all producers from sending messages. 2. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 3. In the navigation pane, choose Queues. 4. On the Queues page, choose a queue. 5. Choose the Monitoring tab. 6. At the top right of the Monitoring dashboards, choose the down arrow next to the Refresh symbol. From the dropdown menu, choose Auto refresh. Leave the Refresh interval at 1 Minute. 7. Observe the following dashboards: • Approximate Number Of Messages Delayed • Approximate Number Of Messages Not Visible • Approximate Number Of Messages Visible When all of them show 0 values for several minutes, the queue is empty. Confirming a queue is empty 25 Amazon Simple Queue Service Developer Guide To confirm that a queue is empty (AWS CLI, AWS API) 1. Stop all producers from sending messages. 2. Repeatedly run one of the following commands: • AWS CLI: get-queue-attributes • AWS API: GetQueueAttributes 3. Observe the metrics for the following attributes: • ApproximateNumberOfMessagesDelayed • ApproximateNumberOfMessagesNotVisible • ApproximateNumberOfMessagesVisible When all of them are 0 for several minutes, the queue is empty. If you rely on Amazon CloudWatch metrics, make sure that you see multiple consecutive zero data points before considering that queue empty. For more information on CloudWatch metrics, see Available CloudWatch metrics for Amazon SQS. Deleting an Amazon SQS queue If you no longer use an Amazon SQS queue and don’t plan to use it in the near future, delete the queue. Tip If you want to verify that a queue is empty before you delete it, see Confirming that an Amazon SQS queue is empty. You can delete a queue even when it isn't empty. To delete the messages in a queue but not the queue itself, purge the queue. To delete a queue (console) 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. Deleting a queue 26 Amazon Simple Queue Service Developer Guide 3. On the Queues page, choose the queue to delete. 4. Choose Delete. 5. In the Delete queue dialog box, confirm the deletion by entering delete. 6. Choose Delete. To delete a queue (AWS CLI and API) Choose the appropriate method to delete your queue based on your needs: • AWS CLI: aws sqs delete-queue • AWS API: DeleteQueue Purging messages from an queue using the Amazon SQS console To keep an Amazon SQS queue but remove all its messages, you can purge the queue. This will delete all messages, including those that are currently invisible (in flight). The purge process can take up to 60 seconds, so wait the full 60 seconds regardless of the queue’s size. Important When you purge a queue, you can't retrieve any of the deleted messages. To purge a queue (console) 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. On the Queues page, choose the queue to purge. 4. 5. From Actions, choose Purge. In the Purge queue dialog box, confirm the purge by entering purge and choosing Purge. • All messages are purged from the queue. The console displays a confirmation banner. Purging a queue 27
sqs-dg-013
sqs-dg.pdf
13
can take up to 60 seconds, so wait the full 60 seconds regardless of the queue’s size. Important When you purge a queue, you can't retrieve any of the deleted messages. To purge a queue (console) 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. On the Queues page, choose the queue to purge. 4. 5. From Actions, choose Purge. In the Purge queue dialog box, confirm the purge by entering purge and choosing Purge. • All messages are purged from the queue. The console displays a confirmation banner. Purging a queue 27 Amazon Simple Queue Service Developer Guide Amazon SQS standard queues Amazon SQS provides standard queues as the default queue type, supporting a nearly unlimited number of API calls per second for actions like SendMessage, ReceiveMessage, and DeleteMessage. Standard queues ensure at-least-once message delivery, but due to the highly distributed architecture, more than one copy of a message might be delivered, and messages may occasionally arrive out of order. Despite this, standard queues make a best-effort attempt to maintain the order in which messages are sent. When you send a message using SendMessage, Amazon SQS redundantly stores the message in multiple availability zones (AZs) before acknowledging it. This redundancy ensures that no single computer, network, or AZ failure can render the messages inaccessible. You can create and configure queues using the Amazon SQS console. For detailed instructions, see Creating a standard queue using the Amazon SQS console. For Java-specific examples, see Amazon SQS Java SDK examples. Use cases for standard queues Standard message queues are suitable for various scenarios, as long as your application can handle messages that might arrive more than once or out of order. Examples include: • Decoupling live user requests from intensive background work – Users can upload media while the system resizes or encodes it in the background. • Allocating tasks to multiple worker nodes – For example, handling a high volume of credit card validation requests. • Batching messages for future processing – Scheduling multiple entries to be added to a database at a later time. For information on quotas related to standard queues, see Amazon SQS standard queue quotas. For best practices of working with standard queues, see Amazon SQS best practices. Amazon SQS at-least-once delivery Amazon SQS stores copies of your messages on multiple servers for redundancy and high availability. On rare occasions, one of the servers that stores a copy of a message might be unavailable when you receive or delete a message. Amazon SQS at-least-once delivery 28 Amazon Simple Queue Service Developer Guide If this occurs, the copy of the message isn't deleted on the server that is unavailable, and you might get that message copy again when you receive messages. Design your applications to be idempotent (they should not be affected adversely when processing the same message more than once). Amazon SQS queue and message identifiers This topic describes the identifiers of standard and FIFO queues. These identifiers can help you find and manipulate specific queues and messages. Identifiers for Amazon SQS standard queues For more information about the following identifiers, see the Amazon Simple Queue Service API Reference. Queue name and URL When you create a new queue, you must specify a queue name unique for your AWS account and region. Amazon SQS assigns each queue you create an identifier called a queue URL that includes the queue name and other Amazon SQS components. Whenever you want to perform an action on a queue, you provide its queue URL. The following is the queue URL for a queue named MyQueue owned by a user with the AWS account number 123456789012. https://sqs.us-east-2.amazonaws.com/123456789012/MyQueue You can retrieve the URL of a queue programmatically by listing your queues and parsing the string that follows the account number. For more information, see ListQueues. Message ID Each message receives a system-assigned message ID that Amazon SQS returns to you in the SendMessage response. This identifier is useful for identifying messages. The maximum length of a message ID is 100 characters. Receipt handle Every time you receive a message from a queue, you receive a receipt handle for that message. This handle is associated with the action of receiving the message, not with the message itself. To Queue and message identifiers 29 Amazon Simple Queue Service Developer Guide delete the message or to change the message visibility, you must provide the receipt handle (not the message ID). Thus, you must always receive a message before you can delete it (you can't put a message into the queue and then recall it). The maximum length of a receipt handle is 1,024 characters. Important If you receive a message more than once, each time you receive it, you get a different receipt handle. You must provide the most
sqs-dg-014
sqs-dg.pdf
14
action of receiving the message, not with the message itself. To Queue and message identifiers 29 Amazon Simple Queue Service Developer Guide delete the message or to change the message visibility, you must provide the receipt handle (not the message ID). Thus, you must always receive a message before you can delete it (you can't put a message into the queue and then recall it). The maximum length of a receipt handle is 1,024 characters. Important If you receive a message more than once, each time you receive it, you get a different receipt handle. You must provide the most recently received receipt handle when you request to delete the message (otherwise, the message might not be deleted). The following is an example of a receipt handle broken across three lines. MbZj6wDWli+JvwwJaBV+3dcjk2YW2vA3+STFFljTM8tJJg6HRG6PYSasuWXPJB+Cw Lj1FjgXUv1uSj1gUPAWV66FU/WeR4mq2OKpEGYWbnLmpRCJVAyeMjeU5ZBdtcQ+QE auMZc8ZRv37sIW2iJKq3M9MFx1YvV11A2x/KSbkJ0= Identifiers for standard queues 30 Amazon Simple Queue Service Developer Guide Amazon SQS FIFO queues FIFO (First-In-First-Out) queues have all the capabilities of the standard queues, but are designed to enhance messaging between applications when the order of operations and events is critical, or where duplicates can't be tolerated. The most important features of FIFO queues are FIFO (First-In-First-Out) delivery and exactly-once processing: • The order in which messages are sent and received is strictly preserved and a message is delivered once and remains unavailable until a consumer processes and deletes it. • Duplicates aren't introduced into the queue. Additionally, FIFO queues support message groups that allow multiple ordered message groups within a single queue. There is no quota to the number of message groups within a FIFO queue. Examples of situations where you might use FIFO queues include the following: 1. E-commerce order management system where order is critical 2. Integrating with a third-party systems where events need to be processed in order 3. Processing user-entered inputs in the order entered 4. Communications and networking – Sending and receiving data and information in the same order 5. Computer systems – Making sure that user-entered commands are run in the right order 6. Educational institutes – Preventing a student from enrolling in a course before registering for an account 7. Online ticketing system – Where tickets are distributed on a first come first serve basis Note FIFO queues also provide exactly-once processing, but have a limited number of transactions per second (TPS). You can use Amazon SQS high throughput mode with your FIFO queue to increase your transaction limit. For details on using high throughput mode, see High throughput for FIFO queues in Amazon SQS. For information on throughput quotas, see the section called “Message quotas”. 31 Amazon Simple Queue Service Developer Guide Amazon SQS FIFO queues are available in all Regions where Amazon SQS is available. For more on using FIFO queues with complex ordering, see Solving Complex Ordering Challenges with Amazon SQS FIFO Queues. For information about how to create and configure queues using the Amazon SQS console, see Creating a standard queue using the Amazon SQS console. For Java examples, see Amazon SQS Java SDK examples. For best practices for working with FIFO queues, see Amazon SQS best practices. Amazon SQS FIFO queue key terms The following key terms can help you better understand the functionality of FIFO queues. For more information, see the Amazon Simple Queue Service API Reference. Clients The Amazon SQS Buffered Asynchronous Client doesn't currently support FIFO queues. Message deduplication ID A token used in Amazon SQS FIFO queues to uniquely identify messages and prevent duplication. If multiple messages with the same deduplication ID are sent within a 5 minute deduplication interval, they are treated as duplicates, and only one copy is delivered. If you don't specify a deduplication ID and content-based deduplication is enabled, Amazon SQS generates a deduplication ID by hashing the message body. This mechanism ensures exactly- once delivery by eliminating duplicate messages within the specified time frame. Note Amazon SQS continues tracking the deduplication ID even after the message has been received and deleted. Message group ID The MessageGroupId is an attribute used only in Amazon SQS FIFO (First-In-First-Out) queues to organize messages into distinct groups. Messages within the same message group are always processed one at a time, in strict order, ensuring that no two messages from the same group are FIFO queue key terms 32 Amazon Simple Queue Service Developer Guide processed simultaneously. Standard queues do not use MessageGroupId and do not provide ordering guarantees. If strict ordering is required, use a FIFO queue instead. Receive request attempt ID The receive request attempt ID is a unique token used to deduplicate ReceiveMessage calls in Amazon SQS. Sequence number The large, non-consecutive number that Amazon SQS assigns to each message. Services If your application uses multiple AWS services, or a mix of AWS and external services, it is important to understand which service functionality
sqs-dg-015
sqs-dg.pdf
15
two messages from the same group are FIFO queue key terms 32 Amazon Simple Queue Service Developer Guide processed simultaneously. Standard queues do not use MessageGroupId and do not provide ordering guarantees. If strict ordering is required, use a FIFO queue instead. Receive request attempt ID The receive request attempt ID is a unique token used to deduplicate ReceiveMessage calls in Amazon SQS. Sequence number The large, non-consecutive number that Amazon SQS assigns to each message. Services If your application uses multiple AWS services, or a mix of AWS and external services, it is important to understand which service functionality doesn't support FIFO queues. Some AWS or external services that send notifications to Amazon SQS might not be compatible with FIFO queues, despite allowing you to set a FIFO queue as a target. The following features of AWS services aren't currently compatible with FIFO queues: • Amazon S3 Event Notifications • Auto Scaling Lifecycle Hooks • AWS IoT Rule Actions • AWS Lambda Dead-Letter Queues For information about compatibility of other services with FIFO queues, see your service documentation. FIFO queue delivery logic in Amazon SQS The following concepts clarify how Amazon SQS FIFO queues handle the sending and receiving of messages, particularly when dealing with message ordering and message group IDs. Sending messages Amazon SQS FIFO queues preserve message order using unique deduplication IDs and message group IDs. This topic highlights the importance of message group IDs for maintaining strict ordering within groups and highlights best practices for ensuring reliable, ordered message delivery across multiple producers. FIFO delivery logic 33 Amazon Simple Queue Service 1. Order preservation Developer Guide • When multiple messages are sent in succession to a FIFO queue with unique message deduplication IDs, Amazon SQS stores them and acknowledges their transmission. These messages are then received and processed in the exact order they were transmitted. 2. Message group ID • In FIFO queues, messages are ordered based on their message group ID. If multiple producers or threads send messages with the same message group ID, Amazon SQS ensures they are stored and processed in the order they arrive. • Best practice: To guarantee strict message order across multiple producers, assign a unique message group ID for all messages from each producer. 3. Per-group ordering • FIFO queue logic applies on a per message group ID basis: • Each message group ID represents a distinct, ordered group of messages. • Within a message group ID, all messages are sent and received in strict order. • Messages with different message group IDs may arrive or be processed out of order relative to one another. • Requirement - You must associate a message group ID with each message. If a message is sent without a group ID, the action fails. • Single group scenario - If you require all messages to be processed in strict order, use the same message group ID for every message. Receiving messages Amazon SQS FIFO queues handle message retrieval, including batch processing, FIFO order guarantees, and limitations on requesting specific message group IDs. This topic explains how Amazon SQS retrieves messages within and across message group IDs while maintaining strict ordering and visibility rules. 1. Batch retrieval • When receiving messages from a FIFO queue with multiple message group IDs, Amazon SQS: • Attempts to return as many messages as possible with the same message group ID in a single call. • Allows other consumers to process messages from different message group IDs concurrently. Receiving messages 34 Amazon Simple Queue Service • Important clarification Developer Guide • You may receive multiple messages from the same message group ID in one batch (up to 10 messages in a single call using the MaxNumberOfMessages parameter). • However, you can't receive additional messages from the same message group ID in subsequent requests until: • The currently received messages are deleted, or • They become visible again (for example, after the visibility timeout expires). 2. FIFO order guarantee • Messages retrieved in a batch retain their FIFO order within the group. • If fewer than 10 messages are available for the same message group ID, Amazon SQS may include messages from other message group IDs in the same batch, but each group retains FIFO order. 3. Consumer limitations • You cannot explicitly request to receive messages from a specific message group ID. Retrying multiple times Producers and consumers can safely retry failed actions in Amazon SQS FIFO queues without disrupting message order or introducing duplicates. This topic highlights how deduplication IDs and visibility timeouts ensure message integrity during retries. 1. Producer retries • If a SendMessage action fails, the producer can retry sending the message multiple times with the same message deduplication ID. • As long as the producer receives at least one acknowledgment before the deduplication interval
sqs-dg-016
sqs-dg.pdf
16
batch, but each group retains FIFO order. 3. Consumer limitations • You cannot explicitly request to receive messages from a specific message group ID. Retrying multiple times Producers and consumers can safely retry failed actions in Amazon SQS FIFO queues without disrupting message order or introducing duplicates. This topic highlights how deduplication IDs and visibility timeouts ensure message integrity during retries. 1. Producer retries • If a SendMessage action fails, the producer can retry sending the message multiple times with the same message deduplication ID. • As long as the producer receives at least one acknowledgment before the deduplication interval expires, retries: • Do not introduce duplicate messages. • Do not disrupt message order. 2. Consumer retries • If a ReceiveMessage action fails, the consumer can retry as many times as necessary using the same receive request attempt ID. • As long as the consumer receives at least one acknowledgment before the visibility timeout expires, retries: Retrying multiple times 35 Amazon Simple Queue Service Developer Guide • Do not disrupt message order. Additional notes on FIFO behavior Learn about handling visibility timeouts, enabling parallel processing with multiple message group IDs, and ensuring strict sequential processing in single-group scenarios. 1. Handling visibility timeout • When a message is retrieved but not deleted, it remains invisible until the visibility timeout expires. • No additional messages from the same message group ID are returned until the first message is deleted or becomes visible again. 2. Concurrency and parallel processing • FIFO queues allow parallel processing of messages across different message group IDs. • To maximize concurrency, design your system with multiple message group IDs for independent workflows. 3. Single group scenarios • For strict sequential processing of all messages in a FIFO queue, use a single message group ID for all messages in the queue. Examples for better understanding The following are practical scenarios illustrating FIFO queue behavior in Amazon SQS. 1. Scenario 1: Single group ID • A producer sends five messages with the same message group ID Group A. • A consumer receives these messages in FIFO order. Until the consumer deletes these messages or the visibility timeout expires, no additional messages from Group A are received. 2. Scenario 2: Multiple group IDs • A producer sends five messages to Group A and 5 to Group B. • Consumer 1 processes messages from Group A, while Consumer 2 processes messages from Group B. This enables parallel processing with strict ordering maintained within each group. 3. Scenario 3: Batch retrieval • A producer sends seven messages to Group A and three to Group B. Additional notes on FIFO behavior 36 Amazon Simple Queue Service Developer Guide • A single consumer retrieves up to 10 messages. If the queue allows, it may return: • Seven messages from Group A and three from Group B (or fewer if fewer messages are available from a single group). Exactly-once processing in Amazon SQS Unlike standard queues, FIFO queues don't introduce duplicate messages. FIFO queues help you avoid sending duplicates to a queue. If you retry the SendMessage action within the 5-minute deduplication interval, Amazon SQS doesn't introduce any duplicates into the queue. To configure deduplication, you must do one of the following: • Enable content-based deduplication. This instructs Amazon SQS to use a SHA-256 hash to generate the message deduplication ID using the body of the message—but not the attributes of the message. For more information, see the documentation on the CreateQueue, GetQueueAttributes, and SetQueueAttributes actions in the Amazon Simple Queue Service API Reference. • Explicitly provide the message deduplication ID (or view the sequence number) for the message. For more information, see the documentation on the SendMessage, SendMessageBatch, and ReceiveMessage actions in the Amazon Simple Queue Service API Reference. Moving from a standard queue to a FIFO queue in Amazon SQS If your existing application uses standard queues and you want to take advantage of the ordering or exactly-once processing features of FIFO queues, you need to configure both the queue and your application correctly. Key considerations • Creating a FIFO Queue: You cannot convert an existing standard queue into a FIFO queue. You must either create a new FIFO queue for your application or delete the existing standard queue and recreate it as a FIFO queue. • Delay Parameter: FIFO queues do not support per-message delays, only per-queue delays. If your application sets the DelaySeconds parameter on each message, you must modify it to set DelaySeconds on the entire queue instead. Exactly-once processing 37 Amazon Simple Queue Service Developer Guide • Message Group ID: Provide a message group ID for every sent message. This ID enables parallel processing of messages while maintaining their respective order. Use a granular business dimension for the message group ID to better scale with FIFO queues. The more message
sqs-dg-017
sqs-dg.pdf
17
delete the existing standard queue and recreate it as a FIFO queue. • Delay Parameter: FIFO queues do not support per-message delays, only per-queue delays. If your application sets the DelaySeconds parameter on each message, you must modify it to set DelaySeconds on the entire queue instead. Exactly-once processing 37 Amazon Simple Queue Service Developer Guide • Message Group ID: Provide a message group ID for every sent message. This ID enables parallel processing of messages while maintaining their respective order. Use a granular business dimension for the message group ID to better scale with FIFO queues. The more message group IDs you distribute messages to, the greater the number of messages available for consumption. • High Throughput Mode: Use the recommended high throughput mode for FIFO queues to achieve increased throughput. For more information on messaging quotas, see Amazon SQS message quotas. Checklist for moving to FIFO queues Before sending messages to a FIFO queue, confirm the following: 1. Configure delay settings • Modify your application to remove per-message delays. • Set the DelaySeconds parameter on the entire queue. 2. Set message group IDs • Organize messages into message groups by specifying a message group ID based on a business dimension. • Use more granular business dimensions to improve scalability. 3. Handle message deduplication • If your application can't send messages with identical message bodies, provide a unique message deduplication ID for each message. • If your application sends messages with unique message bodies, enable content-based deduplication. 4. Configure the consumer • Generally, no code changes are needed for the consumer. • If processing messages takes a long time and the visibility timeout is set high, consider adding a receive request attempt ID to each ReceiveMessage action. This helps retry receive attempts in case of networking failures and prevents queues from pausing due to failed receive attempts. By following these steps, you can ensure your application works correctly with FIFO queues, taking full advantage of their ordering and exactly-once processing features. For more detailed information, see the Amazon Simple Queue Service API Reference. Moving from a standard queue to a FIFO queue 38 Amazon Simple Queue Service Developer Guide Amazon SQS FIFO queue and Lambda concurrency behavior By using a FIFO (First-In-First-Out) queue with Lambda, you can ensure ordered processing of messages within each message group. The Lambda function will not run multiple instances for the same message group simultaneously, thereby maintaining the order. However, it can scale up to handle multiple message groups in parallel, ensuring efficient processing of your queue's workload. The following points describe the behavior of Lambda functions when processing messages from an Amazon SQS FIFO queue with respect to message group IDs: • Single instance per message group: At any point in time, only one Lambda instance will be processing messages from a specific message group ID. This ensures that messages within the same group are processed in order, maintaining the integrity of the FIFO sequence. • Concurrent processing of different groups: Lambda can concurrently process messages from different message group IDs using multiple instances. This means that while one instance of the Lambda function is handling messages from one message group ID, other instances can simultaneously handle messages from other message group IDs, leveraging the concurrency capabilities of Lambda to process multiple groups in parallel. FIFO queue message grouping FIFO queues ensure that messages are processed in the exact order they are sent. They use a message group ID to group messages that should be processed sequentially. Messages within the same message group are processed in order, and only one message from each group is processed at a time to maintain this order. Lambda concurrency with FIFO queues After you create your queue, you can send a message to it. When you set up a Lambda function to process messages from an Amazon SQS FIFO queue, Lambda respects the ordering guarantees provided by the FIFO queue. The following points describe the behavior of Lambda functions in terms of concurrency and scaling when processing messages from an Amazon SQS FIFO queue when using message group IDs. • Concurrency within message groups: Only one Lambda instance processes messages for a particular message group ID at a time. This ensures that messages within a group are handled sequentially. FIFO queue and Lambda concurrency behavior 39 Amazon Simple Queue Service Developer Guide • Scaling and multiple message groups:While Lambda can scale up to process messages concurrently, this scaling occurs across different message groups. If you have multiple message groups, Lambda can process multiple groups in parallel, with each group being handled by a separate Lambda instance. For more information, see Scaling and concurrency in Lambda in the AWS Lambda Operator Guide. Use case example Suppose your FIFO queue receives messages with the same message group ID, and
sqs-dg-018
sqs-dg.pdf
18
a time. This ensures that messages within a group are handled sequentially. FIFO queue and Lambda concurrency behavior 39 Amazon Simple Queue Service Developer Guide • Scaling and multiple message groups:While Lambda can scale up to process messages concurrently, this scaling occurs across different message groups. If you have multiple message groups, Lambda can process multiple groups in parallel, with each group being handled by a separate Lambda instance. For more information, see Scaling and concurrency in Lambda in the AWS Lambda Operator Guide. Use case example Suppose your FIFO queue receives messages with the same message group ID, and your Lambda function has a high concurrency limit (up to 1000). If a message from group ID 'A' is being processed and another message from group ID 'A' arrives, the second message will not trigger a new Lambda instance until the first message is fully processed. However, if messages from group IDs 'A' and 'B' arrive, both messages can be processed concurrently by separate Lambda instances. High throughput for FIFO queues in Amazon SQS High throughput FIFO queues in Amazon SQS efficiently manage high message throughput while maintaining strict message order, ensuring reliability and scalability for applications processing numerous messages. This solution is ideal for scenarios demanding both high throughput and ordered message delivery. Amazon SQS high throughput FIFO queues are not necessary in scenarios where strict message ordering is not crucial and where the volume of incoming messages is relatively low or sporadic. For instance, if you have a small-scale application that processes infrequent or non-sequential messages, the added complexity and cost associated with high throughput FIFO queues may not be justified. Additionally, if your application does not require the enhanced throughput capabilities provided by high throughput FIFO queues, opting for a standard Amazon SQS queue might be more cost-effective and simpler to manage. To enhance request capacity in high throughput FIFO queues, increasing the number of message groups is recommended. For more information on high throughput message quotas, see Amazon SQS service quotas in the Amazon Web Services General Reference. Use case example 40 Amazon Simple Queue Service Developer Guide For information per-queue quotas and data distribution strategies, see Amazon SQS message quotas and Partitions and data distribution for high throughput for SQS FIFO queues. Use cases for high throughput for Amazon SQS FIFO queues The following use cases highlight the diverse applications of high throughput FIFO queues, showcasing their effectiveness across industries and scenarios: 1. Real-time data processing: Applications dealing with real-time data streams, such as event processing or telemetry data ingestion, can benefit from high throughput FIFO queues to handle the continuous influx of messages while preserving their order for accurate analysis. 2. E-commerce order processing: In e-commerce platforms where maintaining the order of customer transactions is critical, high throughput FIFO queues ensure that orders are processed sequentially and without delays, even during peak shopping seasons. 3. Financial services: Financial institutions handling high-frequency trading or transactional data rely on high throughput FIFO Queues to process market data and transactions with minimal latency while adhering to strict regulatory requirements for message ordering. 4. Media streaming: Streaming platforms and media distribution services utilize high throughput FIFO queues to manage the delivery of media files and streaming content, ensuring smooth playback experiences for users while maintaining the correct order of content delivery. Partitions and data distribution for high throughput for SQS FIFO queues Amazon SQS stores FIFO queue data in partitions. A partition is an allocation of storage for a queue that is automatically replicated across multiple Availability Zones within an AWS Region. You don't manage partitions. Instead, Amazon SQS handles partition management. For FIFO queues, Amazon SQS modifies the number of partitions in a queue in the following situations: • If the current request rate approaches or exceeds what the existing partitions can support, additional partitions are allocated until the queue reaches the regional quota. For information on quotas, see Amazon SQS message quotas. • If the current partitions have low utilization, the number of partitions may be reduced. Use cases 41 Amazon Simple Queue Service Developer Guide Partition management occurs automatically in the background and is transparent to your applications. Your queue and messages are available at all times. Distributing data by message group IDs To add a message to a FIFO queue, Amazon SQS uses the value of each message’s message group ID as input to an internal hash function. The output value from the hash function determines which partition stores the message. The following diagram shows a queue that spans multiple partitions. The queue’s message group ID is based on item number. Amazon SQS uses its hash function to determine where to store a new item; in this case, it's based on the hash value of the string item0. Note that the items are stored
sqs-dg-019
sqs-dg.pdf
19
all times. Distributing data by message group IDs To add a message to a FIFO queue, Amazon SQS uses the value of each message’s message group ID as input to an internal hash function. The output value from the hash function determines which partition stores the message. The following diagram shows a queue that spans multiple partitions. The queue’s message group ID is based on item number. Amazon SQS uses its hash function to determine where to store a new item; in this case, it's based on the hash value of the string item0. Note that the items are stored in the same order in which they are added to the queue. Each item's location is determined by the hash value of its message group ID. Note Amazon SQS is optimized for uniform distribution of items across a FIFO queue's partitions, regardless of the number of partitions. AWS recommends that you use message group IDs that can have a large number of distinct values. Partitions and data distribution 42 Amazon Simple Queue Service Developer Guide Optimizing partition utilization Each partition supports up to 3,000 messages per second with batching, or up to 300 messages per second for send, receive, and delete operations in supported regions. For more information on high throughput message quotas, see Amazon SQS service quotas in the Amazon Web Services General Reference. When using batch APIs, each message is routed based on the process described in Distributing data by message group IDs. Messages that are routed to the same partition are grouped and processed in a single transaction. To optimize partition utilization for the SendMessageBatch API, AWS recommends batching messages with the same message group IDs when possible. To optimize partition utilization for the DeleteMessageBatch and ChangeMessageVisibilityBatch APIs, AWS recommends using ReceiveMessage requests with the MaxNumberOfMessages parameter set to 10, and batching the receipt-handles returned by a single ReceiveMessage request. In the following example, a batch of messages with various message group IDs is sent. The batch is split into three groups, each of which counts against the quota for the partition. Partitions and data distribution 43 Amazon Simple Queue Service Developer Guide Note Amazon SQS only guarantees that messages with the same message group ID's internal hash function are grouped within a batch request. Depending on the output of the internal hash function and the number of partitions, messages with different message group IDs might be grouped. Since the hash function or number of partitions can change at any time, messages that are grouped at one point may not be grouped later. Enabling high throughput for FIFO queues in Amazon SQS You can enable high throughput for any new or existing FIFO queue. The feature includes three new options when you create and edit FIFO queues: • Enable high throughput FIFO – Makes higher throughput available for messages in the current FIFO queue. • Deduplication scope – Specifies whether deduplication occurs at the queue or message group level. • FIFO throughput limit – Specifies whether the throughput quota on messages in the FIFO queue is set at the queue or message group level. To enable high throughput for a FIFO queue (console) 1. Start creating or editing a FIFO queue. 2. When specifying options for the queue, choose Enable high throughput FIFO. Enabling high throughput for FIFO queues sets the related options as follows: • Deduplication scope is set to Message group, the required setting for using high throughput for FIFO queues. • FIFO throughput limit is set to Per message group ID, the required setting for using high throughput for FIFO queues. If you change any of the settings required for using high throughput for FIFO queues, normal throughput is in effect for the queue, and deduplication occurs as specified. 3. Continue specifying all options for the queue. When you finish, choose Create queue or Save. Enabling high throughput for FIFO queues 44 Amazon Simple Queue Service Developer Guide After creating or editing the FIFO queue, you can send messages to it and receive and delete messages, all at a higher TPS. For high throughput quotas, see Message throughput in Amazon SQS message quotas. FIFO queue and message identifiers in Amazon SQS This section describes the identifiers of FIFO queues. These identifiers can help you find and manipulate specific queues and messages. Identifiers for FIFO queues in Amazon SQS For more information about the following identifiers, see the Amazon Simple Queue Service API Reference. Queue name and URL When you create a new queue, you must specify a queue name unique for your AWS account and region. Amazon SQS assigns each queue you create an identifier called a queue URL that includes the queue name and other Amazon SQS components. Whenever you want to perform an action on a queue, you provide its queue URL.
sqs-dg-020
sqs-dg.pdf
20
the identifiers of FIFO queues. These identifiers can help you find and manipulate specific queues and messages. Identifiers for FIFO queues in Amazon SQS For more information about the following identifiers, see the Amazon Simple Queue Service API Reference. Queue name and URL When you create a new queue, you must specify a queue name unique for your AWS account and region. Amazon SQS assigns each queue you create an identifier called a queue URL that includes the queue name and other Amazon SQS components. Whenever you want to perform an action on a queue, you provide its queue URL. The name of a FIFO queue must end with the .fifo suffix. The suffix counts towards the 80- character queue name quota. To determine whether a queue is FIFO, you can check whether the queue name ends with the suffix. The following is the queue URL for a FIFO queue named MyQueue owned by a user with the AWS account number 123456789012. https://sqs.us-east-2.amazonaws.com/123456789012/MyQueue.fifo You can retrieve the URL of a queue programmatically by listing your queues and parsing the string that follows the account number. For more information, see ListQueues. Message ID Each message receives a system-assigned message ID that Amazon SQS returns to you in the SendMessage response. This identifier is useful for identifying messages. The maximum length of a message ID is 100 characters. Queue and message identifiers 45 Amazon Simple Queue Service Receipt handle Developer Guide Every time you receive a message from a queue, you receive a receipt handle for that message. This handle is associated with the action of receiving the message, not with the message itself. To delete the message or to change the message visibility, you must provide the receipt handle (not the message ID). Thus, you must always receive a message before you can delete it (you can't put a message into the queue and then recall it). The maximum length of a receipt handle is 1,024 characters. Important If you receive a message more than once, each time you receive it, you get a different receipt handle. You must provide the most recently received receipt handle when you request to delete the message (otherwise, the message might not be deleted). The following is an example of a receipt handle (broken across three lines). MbZj6wDWli+JvwwJaBV+3dcjk2YW2vA3+STFFljTM8tJJg6HRG6PYSasuWXPJB+Cw Lj1FjgXUv1uSj1gUPAWV66FU/WeR4mq2OKpEGYWbnLmpRCJVAyeMjeU5ZBdtcQ+QE auMZc8ZRv37sIW2iJKq3M9MFx1YvV11A2x/KSbkJ0= Additional identifiers for Amazon SQS FIFO queues For more information about the following identifiers, see Exactly-once processing in Amazon SQS and the Amazon Simple Queue Service API Reference. Message deduplication ID A token used in Amazon SQS FIFO queues to uniquely identify messages and prevent duplication. If multiple messages with the same deduplication ID are sent within a 5 minute deduplication interval, they are treated as duplicates, and only one copy is delivered. If you don't specify a deduplication ID and content-based deduplication is enabled, Amazon SQS generates a deduplication ID by hashing the message body. This mechanism ensures exactly-once delivery by eliminating duplicate messages within the specified time frame. Message group ID The MessageGroupId is an attribute used only in Amazon SQS FIFO (First-In-First-Out) queues to organize messages into distinct groups. Messages within the same message group are always Additional identifiers for FIFO queues 46 Amazon Simple Queue Service Developer Guide processed one at a time, in strict order, ensuring that no two messages from the same group are processed simultaneously. Standard queues do not use MessageGroupId and do not provide ordering guarantees. If strict ordering is required, use a FIFO queue instead. Sequence number The large, non-consecutive number that Amazon SQS assigns to each message. Additional identifiers for FIFO queues 47 Amazon Simple Queue Service Developer Guide Amazon SQS quotas This topic explains the quotas and limitations for Amazon SQS FIFO and standard queues, detailing how they impact queue creation, configuration, and message handling. Learn about constraints like message retention limits, in-flight message caps, and throughput thresholds, as well as strategies to maximize efficiency through batching, API call optimization, and long polling. This topic also covers naming conventions, tagging rules, and methods for requesting quota increases to meet high-demand workloads, ensuring effective queue management and optimal performance. Amazon SQS FIFO queue quotas Amazon SQS quotas The following table lists quotas related to FIFO queues. Quota Delay queue Description The default (minimum) delay for a queue is 0 seconds. The maximum is 15 minutes. Listed queues 1,000 queues per ListQueues request. Long polling wait time The maximum long polling wait time is 20 seconds. Message groups There is no quota to the number of message groups within a FIFO queue. Messages per queue (backlog) The number of messages that an Amazon SQS queue can store is unlimited. Messages per queue (in flight) FIFO queues support a maximum of 120,000 in-flight messages (messages received by a consumer but not yet deleted). If this limit is
sqs-dg-021
sqs-dg.pdf
21
queues. Quota Delay queue Description The default (minimum) delay for a queue is 0 seconds. The maximum is 15 minutes. Listed queues 1,000 queues per ListQueues request. Long polling wait time The maximum long polling wait time is 20 seconds. Message groups There is no quota to the number of message groups within a FIFO queue. Messages per queue (backlog) The number of messages that an Amazon SQS queue can store is unlimited. Messages per queue (in flight) FIFO queues support a maximum of 120,000 in-flight messages (messages received by a consumer but not yet deleted). If this limit is reached, Amazon SQS does not return an error, but processing may be impacted. You can request an increase beyond this limit by contacting AWS Support. FIFO queue quotas 48 Amazon Simple Queue Service Developer Guide Quota Queue name Queue tag Description The name of a FIFO queue must end with the .fifo suffix. The suffix counts towards the 80-character queue name quota. To determine whether a queue is FIFO, you can check whether the queue name ends with the suffix. We don't recommend adding more than 50 tags to a queue. Tagging supports Unicode characters in UTF-8. The tag Key is required, but the tag Value is optional. The tag Key and tag Value are case-sensitive. The tag Key and tag Value can include Unicode alphanumeric characters in UTF-8 and whitespaces. The following special characters are allowed: _ . : / = + - @ The tag Key or Value must not include the reserved prefix aws: (you can't delete tag keys or values with this prefix). The maximum tag Key length is 128 Unicode characters in UTF-8. The tag Key must not be empty or null. The maximum tag Value length is 256 Unicode characters in UTF-8. The tag Value may be empty or null. Tagging actions are limited to 30 TPS per AWS account. If your application requires a higher throughput, submit a request. Amazon SQS standard queue quotas The following table lists quotas related to standard queues. Standard queue quotas 49 Amazon Simple Queue Service Developer Guide Quota Delay queue Description The default (minimum) delay for a queue is 0 seconds. The maximum is 15 minutes. Listed queues 1,000 queues per ListQueues request. Long polling wait time The maximum long polling wait time is 20 seconds. Messages per queue (backlog) The number of messages that an Amazon SQS queue can store is unlimited. Messages per queue (in flight) Queue name For most standard queues (depending on queue traffic and message backlog), there can be a maximum of approximately 120,000 in flight messages (received from a queue by a consumer, but not yet deleted from the queue). If you reach this quota while using short polling, Amazon SQS returns the OverLimit error message. If you use long polling, Amazon SQS returns no error messages. To avoid reaching the quota, you should delete messages from the queue after they're processed. You can also increase the number of queues you use to process your messages. To request a quota increase, submit a support request. A queue name can have up to 80 characters. The following characters are accepted: alphanumeric characters, hyphens (-), and underscores (_). Note Queue names are case-sensitive (for example, Test-queue and test-queue are different queues). Queue tag We don't recommend adding more than 50 tags to a queue. Tagging supports Unicode characters in UTF-8. Standard queue quotas 50 Amazon Simple Queue Service Developer Guide Quota Description The tag Key is required, but the tag Value is optional. The tag Key and tag Value are case-sensitive. The tag Key and tag Value can include Unicode alphanumeric characters in UTF-8 and whitespaces. The following special characters are allowed: _ . : / = + - @ The tag Key or Value must not include the reserved prefix aws: (you can't delete tag keys or values with this prefix). The maximum tag Key length is 128 Unicode characters in UTF-8. The tag Key must not be empty or null. The maximum tag Value length is 256 Unicode characters in UTF-8. The tag Value may be empty or null. Tagging actions are limited to 30 TPS per AWS account. If your application requires a higher throughput, submit a request. Amazon SQS message quotas The following table lists quotas related to messages. Quota Description Batched message ID A batched message ID can have up to 80 characters. The following characters are accepted: alphanumeric characters, hyphens (-), and underscores (_). Message attributes A message can contain up to 10 metadata attributes. Message quotas 51 Amazon Simple Queue Service Developer Guide Quota Message batch Message content Message group ID Message retention Description A single message batch request can include a maximum of 10 messages. For more information, see Configuring AmazonSQSBufferedAsyncClient in the Amazon SQS
sqs-dg-022
sqs-dg.pdf
22
application requires a higher throughput, submit a request. Amazon SQS message quotas The following table lists quotas related to messages. Quota Description Batched message ID A batched message ID can have up to 80 characters. The following characters are accepted: alphanumeric characters, hyphens (-), and underscores (_). Message attributes A message can contain up to 10 metadata attributes. Message quotas 51 Amazon Simple Queue Service Developer Guide Quota Message batch Message content Message group ID Message retention Description A single message batch request can include a maximum of 10 messages. For more information, see Configuring AmazonSQSBufferedAsyncClient in the Amazon SQS batch actions section. A message can include only XML, JSON, and unformatt ed text. The following Unicode characters are allowed: #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF Any characters not included in this list are rejected. For more information, see the W3C specification for characters. Consume messages from the backlog to avoid building up a large backlog of messages with the same message group ID. MessageGroupId is required for FIFO queues. You can't use it for Standard queues. You must associate a non-empty MessageGroupId with a message. If you don't provide a MessageGr oupId , the action fails. The length of MessageGroupId is 128 characters. Valid values: alphanumeric characters and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~) . By default, a message is retained for 4 days. The minimum is 60 seconds (1 minute). The maximum is 1,209,600 seconds (14 days). Message quotas 52 Amazon Simple Queue Service Developer Guide Quota Description Message throughput Standard queues Standard queues support a very high, nearly unlimited number of API calls per second, per action (SendMessa ge , ReceiveMessage , or DeleteMessage ). This high throughput makes them ideal for use cases that require processing large volumes of messages quickly, such as real-time data streaming or large-scale applicati ons. While standard queues scale automatically with demand, it is essential to monitor usage patterns to ensure optimal performance, especially in regions with higher workloads. Message quotas 53 Amazon Simple Queue Service Developer Guide Quota Description FIFO queues • Each partition in a FIFO queue is limited to 300 transactions per second, per API action (SendMessa ge , ReceiveMessage , and DeleteMessage ). This limit applies specifically to non-high throughput mode. By switching to high throughput mode, you can surpass this default limit. To enable high-throughput mode, see Enabling high throughput for FIFO queues in Amazon SQS. • If you use batching, non-high throughput FIFO queues support up to 3,000 messages per second, per API action (SendMessage , ReceiveMessage , and DeleteMessage ). The 3,000 messages per second represent 300 API calls, each with a batch of 10 messages. High throughput for FIFO queues Amazon SQS FIFO limits are based on the number of API requests, not message limits. For high throughput mode, these API request limits are as follows: Transaction throughput limits (Non-batching API calls) These limits define how frequently each API operation (such as SendMessage, ReceiveMessage, or DeleteMes sage) can be performed independently, ensuring efficient system performance within the allowed transactions per second (TPS). The following limits are based on non-batched API calls: • US East (N. Virginia), US West (Oregon), and Europe (Ireland): Up to 70,000 transactions per second (TPS). Message quotas 54 Amazon Simple Queue Service Developer Guide Quota Description • US East (Ohio) and Europe (Frankfurt): Up to 19,000 TPS. • Asia Pacific (Mumbai), Asia Pacific (Singapore), Asia Pacific (Sydney), and Asia Pacific (Tokyo): Up to 9,000 TPS. • Europe (London) and South America (São Paulo): Up to 4,500 TPS. • All other AWS Regions: Default throughput of 2,400 TPS. Maximizing throughput with batching Processes multiple messages in a single API call, which significantly increasing efficiency. Instead of handling each message individually, batching allows you to send, receive, or delete up to 10 messages in a single API request. This reduces the total number of API calls, allowing you to process more messages per second while staying within the transaction limits (TPS) for the region, maximizing throughput and system performan ce. For more information, see Increasing throughput usi ng horizontal scaling and action batching with Amazon SQS. The following limits are based on batched API calls: • US East (N. Virginia), US West (Oregon), and Europe (Ireland): Up to 700,000 messages per second (10x the non-batch limit of 70,000 TPS). • US East (Ohio) and Europe (Frankfurt): Up to 190,000 messages per second. • Asia Pacific (Mumbai), Asia Pacific (Singapore), Asia Pacific (Sydney), and Asia Pacific (Tokyo): Up to 90,000 messages per second. Message quotas 55 Amazon Simple Queue Service Developer Guide Quota Description • Europe (London) and South America (São Paulo): Up to 45,000 messages per second. • All other AWS Regions: Up to 24,000 messages per second. Optimizing throughput beyond batching While batching
sqs-dg-023
sqs-dg.pdf
23
calls: • US East (N. Virginia), US West (Oregon), and Europe (Ireland): Up to 700,000 messages per second (10x the non-batch limit of 70,000 TPS). • US East (Ohio) and Europe (Frankfurt): Up to 190,000 messages per second. • Asia Pacific (Mumbai), Asia Pacific (Singapore), Asia Pacific (Sydney), and Asia Pacific (Tokyo): Up to 90,000 messages per second. Message quotas 55 Amazon Simple Queue Service Developer Guide Quota Description • Europe (London) and South America (São Paulo): Up to 45,000 messages per second. • All other AWS Regions: Up to 24,000 messages per second. Optimizing throughput beyond batching While batching can greatly increase throughput, it’s important to consider other strategies for optimizing FIFO performance: • Distribute messages across multiple message group IDs – Since messages within a single group are processed sequentially, distributing your workload across multiple message groups allows for better parallelism and higher overall throughput. For more information, see Partitions and data distribution for high throughput for SQS FIFO queues. • Efficient use of API calls – Minimize unnecessa ry API calls, such as frequent visibility changes or repeated message deletions, to optimize the use of your available TPS and improve efficiency. • Use long poll receives – Utilize long polling by setting WaitTimeSeconds in your receive requests to reduce empty responses when no messages are available, lowering unnecessary API calls and making better use of your TPS quota. • Requesting throughput increases – If your applicati on requires throughput higher than the default limits, request an increase using the Service Quotas console. This can be necessary for high-demand workloads or in regions with lower default limits. To enable high- throughput mode, see Enabling high throughput for FIFO queues in Amazon SQS. Message quotas 56 Amazon Simple Queue Service Developer Guide Quota Message timer Message size Description The default (minimum) delay for a message is 0 seconds. The maximum is 15 minutes. The minimum message size is 1 byte (1 character). The maximum is 262,144 bytes (256 KiB). To send messages larger than 256 KiB, you can use the Amazon SQS Extended Client Library for Java and the Amazon SQS Extended Client Library for Python. This library allows you to send an Amazon SQS message that contains a reference to a message payload in Amazon S3. The maximum payload size is 2 GB. Note This extended library works only for synchrono us clients. Message visibility timeout The default visibility timeout for a message is 30 seconds. The minimum is 0 seconds. The maximum is 12 Policy information hours. The maximum quota is 8,192 bytes, 20 statements, 50 principals, or 10 conditions. For more information, see Amazon SQS policy quotas. Amazon SQS policy quotas The following table lists quotas related to policies. Name Bytes Conditions Policy quotas Maximum 8,192 10 57 Amazon Simple Queue Service Developer Guide Name Principals Statements Actions per statement Maximum 50 20 7 Policy quotas 58 Amazon Simple Queue Service Developer Guide Amazon SQS features and capabilities This topic provides commonly used features in Amazon SQS for managing message queues, optimizing performance, ensuring reliable message delivery, and handling message processing efficiently. Using dead-letter queues in Amazon SQS Amazon SQS supports dead-letter queues (DLQs), which source queues can target for messages that are not processed successfully. DLQs are useful for debugging your application because you can isolate unconsumed messages to determine why processing did not succeed. For optimal performance, it is a best practice to keep the source queue and DLQ within the same AWS account and Region. Once messages are in a dead-letter queue, you can: • Examine logs for exceptions that might have caused messages to be moved to a dead-letter queue. • Analyze the contents of messages moved to the dead-letter queue to diagnose application issues. • Determine whether you have given your consumer sufficient time to process messages. • Move messages out of the dead-letter queue using dead-letter queue redrive. You must first create a new queue before configuring it as a dead-letter queue. For information about configuring a dead-letter queue using the Amazon SQS console, see Configure a dead-letter queue using the Amazon SQS console. For help with dead-letter queues, such as how to configure an alarm for any messages moved to a dead-letter queue, see Creating alarms for dead-letter queues using Amazon CloudWatch. Note Don't use a dead-letter queue with a FIFO queue if you don't want to break the exact order of messages or operations. For example, don't use a dead-letter queue with instructions in an Edit Decision List (EDL) for a video editing suite, where changing the order of edits changes the context of subsequent edits. Dead-letter queues 59 Amazon Simple Queue Service Developer Guide Using policies for dead-letter queues Use a redrive policy to specify the maxReceiveCount. The maxReceiveCount is the number of times a consumer can
sqs-dg-024
sqs-dg.pdf
24
to a dead-letter queue, see Creating alarms for dead-letter queues using Amazon CloudWatch. Note Don't use a dead-letter queue with a FIFO queue if you don't want to break the exact order of messages or operations. For example, don't use a dead-letter queue with instructions in an Edit Decision List (EDL) for a video editing suite, where changing the order of edits changes the context of subsequent edits. Dead-letter queues 59 Amazon Simple Queue Service Developer Guide Using policies for dead-letter queues Use a redrive policy to specify the maxReceiveCount. The maxReceiveCount is the number of times a consumer can receive a message from a source queue before it is moved to a dead-letter queue. For example, if the maxReceiveCount is set to a low value such as 1, one failure to receive a message would cause the message to move to the dead-letter queue. To ensure that your system is resilient against errors, set the maxReceiveCount high enough to allow for sufficient retries. The redrive allow policy specifies which source queues can access the dead-letter queue. You can choose whether to allow all source queues, allow specific source queues, or deny all source queues use of the dead-letter queue. The default allows all source queues to use the dead-letter queue. If you choose to allow specific queues using the byQueue option, you can specify up to 10 source queues using the source queue Amazon Resource Name (ARN). If you specify denyAll, the queue cannot be used as a dead-letter queue. Understanding message retention periods for dead-letter queues For standard queues, the expiration of a message is always based on its original enqueue timestamp. When a message is moved to a dead-letter queue, the enqueue timestamp is unchanged. The ApproximateAgeOfOldestMessage metric indicates when the message moved to the dead-letter queue, not when the message was originally sent. For example, assume that a message spends 1 day in the original queue before it's moved to a dead-letter queue. If the dead-letter queue's retention period is 4 days, the message is deleted from the dead-letter queue after 3 days and the ApproximateAgeOfOldestMessage is 3 days. Thus, it is a best practice to always set the retention period of a dead-letter queue to be longer than the retention period of the original queue. For FIFO queues, the enqueue timestamp resets when the message is moved to a dead-letter queue. The ApproximateAgeOfOldestMessage metric indicates when the message moved to the dead-letter queue. In the same example above, the message is deleted from the dead-letter queue after four days and the ApproximateAgeOfOldestMessage is four days. Configure a dead-letter queue using the Amazon SQS console A dead-letter queue (DLQ) is a queue that receives messages that were not successfully processed from another queue, known as the source queue. Amazon SQS does not create the dead-letter queue automatically. You must first create the queue before using it as a dead-letter queue. When configuring a DLQ, the queue type must match the source queue type—a FIFO queue can only use Using policies for dead-letter queues 60 Amazon Simple Queue Service Developer Guide a FIFO DLQ, and a standard queue can only use a standard DLQ. You can configure a dead-letter queue when you create or edit a queue. For more details, see Using dead-letter queues in Amazon SQS . To configure a dead-letter queue for an existing queue (console) 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. 3. In the navigation pane, choose Queues. Select the source queue (the queue that will send failed messages to the dead-letter queue), then choose Edit. 4. Scroll to the Dead-letter queue section and toggle Enabled. 5. Under Dead-letter queue settings, choose the Amazon Resource Name (ARN) of an existing queue that you want to use as the dead-letter queue. 6. Set the Maximum receives value, which defines how many times a message can be received before being sent to the dead-letter queue (valid range: 1 to 1,000). 7. Choose Save. Learn how to configure a dead-letter queue redrive in Amazon SQS Use dead-letter queue redrive to move unconsumed messages from a dead-letter queue to another destination for processing. By default, dead-letter queue redrive moves messages from a dead- letter queue to a source queue. However, you can also configure any other queue as the redrive destination if both queues are the same type. For example, if the dead-letter queue is a FIFO queue, the redrive destination queue must be a FIFO queue as well. Additionally, you can configure the redrive velocity to set the rate at which Amazon SQS moves messages. Note When a message is moved from a FIFO queue to a FIFO DLQ, the original message's deduplication ID will be replaced with the original message's ID. This is to make sure that the DLQ deduplication will not prevent
sqs-dg-025
sqs-dg.pdf
25
to a source queue. However, you can also configure any other queue as the redrive destination if both queues are the same type. For example, if the dead-letter queue is a FIFO queue, the redrive destination queue must be a FIFO queue as well. Additionally, you can configure the redrive velocity to set the rate at which Amazon SQS moves messages. Note When a message is moved from a FIFO queue to a FIFO DLQ, the original message's deduplication ID will be replaced with the original message's ID. This is to make sure that the DLQ deduplication will not prevent storing of two independent messages that happen to share a deduplication ID. Dead-letter queues redrive messages in the order they are received, starting with the oldest message. However, the destination queue ingests the redriven messages, as well as new messages Configuring a dead-letter queue redrive 61 Amazon Simple Queue Service Developer Guide from other producers, according to the order in which it receives them. For example, if a producer is sending messages to a source FIFO queue when simultaneously receiving redriven messages from a dead letter queue, the redriven messages will interweave with the new messages from the producer. Note The redrive task resets the retention period. All redriven messages are considered new messages with a new messageID and enqueueTime are assigned to redriven messages. Configuring a dead-letter queue redrive for an existing standard queue using the Amazon SQS API You can configure a dead-letter queue redrive using the StartMessageMoveTask, ListMessageMoveTasks, and CancelMessageMoveTask API actions: API action Description StartMessageMoveTask ListMessageMoveTasks CancelMessageMoveTask Starts an asynchronous task to move messages from a specified source queue to a specified destination queue. Gets the most recent message movement tasks (up to 10) under a specific source queue. Cancels a specified message movement task. A message movement can only be cancelled when the current status is RUNNING. Configuring a dead-letter queue redrive for an existing standard queue using the Amazon SQS console 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. Choose the name of queue that you have configured as a dead-letter queue. Configuring a dead-letter queue redrive 62 Amazon Simple Queue Service 4. Choose Start DLQ redrive. Developer Guide 5. Under Redrive configuration, for Message destination, do either of the following: • • To redrive messages to their source queue, choose Redrive to source queue(s). To redrive messages to another queue, choose Redrive to custom destination. Then, enter the Amazon Resource Name (ARN) of an existing destination queue. 6. Under Velocity control settings, choose one of the following: • System optimized - Redrive dead-letter queue messages at the maximum number of messages per second. • Custom max velocity - Redrive dead-letter queue messages with a custom maximum rate of messages per second. The maximum allowed rate is 500 messages per second. • It is recommended to start with a small value for Custom max velocity and verify that the source queue doesn't get overwhelmed with messages. From there, gradually ramp-up the Custom max velocity value, continuing to monitor the state of the source queue. 7. When you finish configuring the dead-letter queue redrive, choose Redrive messages. Important Amazon SQS doesn't support filtering and modifying messages while redriving them from the dead-letter queue. A dead-letter queue redrive task can run a maximum of 36 hours. Amazon SQS supports a maximum of 100 active redrive tasks per account. 8. If you want to cancel the message redrive task, on the Details page for your queue, choose Cancel DLQ redrive. When canceling an in progress message redrive, any messages that have already been successfully moved to their move destination queue will remain in the destination queue. Configuring queue permissions for dead-letter queue redrive You can give user access to specific dead-letter queue actions by adding permissions to your policy. The minimum required permissions for a dead-letter queue redrive are as follows: Configuring a dead-letter queue redrive 63 Amazon Simple Queue Service Developer Guide Minimum Permissions To start a message redrive To cancel an in- progress message redrive To show a message move status Required API methods • • • • Add the sqs:StartMessageMoveTask , sqs:ReceiveMessage , sqs:DeleteMessage , and sqs:GetQueueAttributes of the dead-letter queue. If either the dead-letter queue or the original source queue are encrypted (also known as an SSE queue), kms:Decry pt for any KMS key that has been used to encrypt the messages is also required. Add the sqs:SendMessage of the destination queue. If the destinati on queue is encrypted, kms:GenerateDataKey and kms:Decry pt are also required. Add the sqs:CancelMessageMoveTask , sqs:ReceiveMessage , sqs:DeleteMessage , and sqs:GetQueueAttributes of the dead-letter queue. If the dead-letter queue is encrypted (also known as an SSE queue), kms:Decrypt is also required. Add the sqs:ListMessageMoveTasks and sqs:GetQu eueAttributes of the dead-letter
sqs-dg-026
sqs-dg.pdf
26
sqs:GetQueueAttributes of the dead-letter queue. If either the dead-letter queue or the original source queue are encrypted (also known as an SSE queue), kms:Decry pt for any KMS key that has been used to encrypt the messages is also required. Add the sqs:SendMessage of the destination queue. If the destinati on queue is encrypted, kms:GenerateDataKey and kms:Decry pt are also required. Add the sqs:CancelMessageMoveTask , sqs:ReceiveMessage , sqs:DeleteMessage , and sqs:GetQueueAttributes of the dead-letter queue. If the dead-letter queue is encrypted (also known as an SSE queue), kms:Decrypt is also required. Add the sqs:ListMessageMoveTasks and sqs:GetQu eueAttributes of the dead-letter queue. To configure permissions for an encrypted queue pair (a source queue with a dead-letter queue) Use the following steps to configure minimum permissions for a dead-letter queue (DLQ) redrive: 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. In the navigation pane, select Policies. 3. Create a new policy and add the following permissions. Attach the policy to the IAM user or role that will perform the redrive operation. • Permissions for the DLQ (source queue): • sqs:StartMessageMoveTask Configuring a dead-letter queue redrive 64 Amazon Simple Queue Service Developer Guide • sqs:CancelMessageMoveTask • sqs:ListMessageMoveTasks • sqs:ReceiveMessage • sqs:DeleteMessage • sqs:GetQueueAttributes • sqs:ListDeadLetterSourceQueues • Specify the Resource ARN of the DLQ (source queue) (for example, "arn:aws:sqs:<DLQ_region>:<DLQ_accountId>:<DLQ_name>"). • Permissions for destination queue: • sqs:SendMessage • Specify the Resource ARN of the destination queue (for example, "arn:aws:sqs:<DestQueue_region>:<DestQueue_accountId>:<DestQueue_name>"). • Permissions for KMS keys: • kms:Decrypt (Needed to decrypt messages in the DLQ.) • kms:GenerateDataKey (Needed to encrypt messages in the destination queue.) • Resource ARNs: • The ARN of the KMS key used to encrypt messages in the DLQ (source queue) (for example, "arn:aws:kms:<region>:<accountId>:key/<SourceQueueKeyId>"). • The ARN of the KMS key used to encrypt messages in the destination queue (for example, "arn:aws:kms:<region>:<accountId>:key/<DestinationQueueKeyId>"). Your access policy should resemble the following: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sqs:StartMessageMoveTask", "sqs:CancelMessageMoveTask", "sqs:ListMessageMoveTasks", "sqs:ReceiveMessage", Configuring a dead-letter queue redrive "sqs:DeleteMessage", 65 Amazon Simple Queue Service Developer Guide "sqs:GetQueueAttributes", "sqs:ListDeadLetterSourceQueues" ], "Resource": "arn:aws:sqs:<DLQ_region>:<DLQ_accountId>:<DLQ_name>", "Condition": { "StringEquals": { "aws:ResourceTag/QueueRole": "source" } } }, { "Effect": "Allow", "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:<DestQueue_region>:<DestQueue_accountId>:<DestQueue_name>", "Condition": { "StringEquals": { "aws:ResourceTag/QueueRole": "destination" } } }, { "Effect": "Allow", "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": [ "arn:aws:kms:<region>:<accountId>:key/<SourceQueueKeyId>", "arn:aws:kms:<region>:<accountId>:key/<DestQueueKeyId>" ] } ] } To configure permissions using a non-encrypted queue pair (a source queue with a dead-letter queue) Follow these steps to configure the minimum permissions required for handling a standard, unencrypted dead-letter queue (DLQ). Required minimum permissions are to receive, delete and get attributes from the dead-letter queue, and send attributes to the source queue. Configuring a dead-letter queue redrive 66 Amazon Simple Queue Service Developer Guide 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. In the navigation pane, select Policies. 3. Create a new policy and add the following permissions. Attach the policy to the IAM user or role that will perform the redrive operation. • Permissions for the DLQ (source queue): • sqs:StartMessageMoveTask • sqs:CancelMessageMoveTask • sqs:ListMessageMoveTasks • sqs:ReceiveMessage • sqs:DeleteMessage • sqs:ListDeadLetterSourceQueues • Specify the Resource ARN of the DLQ (source queue) (for example, "arn:aws:sqs:<DLQ_region>:<DLQ_accountId>:<DLQ_name>"). • Permissions for destination queue: • sqs:SendMessage • Specify the Resource ARN of the destination queue (for example, "arn:aws:sqs:<DestQueue_region>:<DestQueue_accountId>:<DestQueue_name>"). Your access policy should resemble the following: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sqs:StartMessageMoveTask", "sqs:CancelMessageMoveTask", "sqs:ListMessageMoveTasks", "sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes", "sqs:ListDeadLetterSourceQueues" ], "Resource": "arn:aws:sqs:<DLQ_region>:<DLQ_accountId>:<DLQ_name>", "Condition": { Configuring a dead-letter queue redrive 67 Amazon Simple Queue Service Developer Guide "StringEquals": { "aws:ResourceTag/QueueRole": "source" } } }, { "Effect": "Allow", "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:<DestQueue_region>:<DestQueue_accountId>:<DestQueue_name>", "Condition": { "StringEquals": { "aws:ResourceTag/QueueRole": "destination" } } } ] } CloudTrail update and permission requirements for Amazon SQS dead- letter queue redrive On June 8, 2023, Amazon SQS introduced dead-letter queue (DLQ) redrive for AWS SDK and AWS Command Line Interface (CLI). This capability is an addition to the already supported DLQ redrive for the AWS console. If you've previously used the AWS console to redrive dead-letter queue messages, you may be affected by the following changes: CloudTrail event renaming On October 15, 2023, the CloudTrail event names for dead-letter queue redrive will change on the Amazon SQS console. If you've set alarms for these CloudTrail events, you must update them now. The following are the new CloudTrail event names for DLQ redrive: Previous event name New event name CreateMoveTask CancelMoveTask StartMessageMoveTask CancelMessageMoveTask CloudTrail update and permission requirements 68 Amazon Simple Queue Service Updated permissions Developer Guide Included with the SDK and CLI release, Amazon SQS has also updated queue permissions for DLQ redrive to adhere to security best practices. Use the following queue permission types to redrive messages from your DLQs. 1. Action-based permissions (update for the DLQ API actions) 2. Managed Amazon SQS policy permissions 3. Permission policy that uses sqs:* wildcard Important To use the DLQ redrive for
sqs-dg-027
sqs-dg.pdf
27
now. The following are the new CloudTrail event names for DLQ redrive: Previous event name New event name CreateMoveTask CancelMoveTask StartMessageMoveTask CancelMessageMoveTask CloudTrail update and permission requirements 68 Amazon Simple Queue Service Updated permissions Developer Guide Included with the SDK and CLI release, Amazon SQS has also updated queue permissions for DLQ redrive to adhere to security best practices. Use the following queue permission types to redrive messages from your DLQs. 1. Action-based permissions (update for the DLQ API actions) 2. Managed Amazon SQS policy permissions 3. Permission policy that uses sqs:* wildcard Important To use the DLQ redrive for SDK or CLI, you are required to have a DLQ redrive permission policy that matches one of the above options. If your queue permissions for DLQ redrive don't match one of the options above, you must update your permissions by August 31, 2023. Between now and August 31, 2023, your account will be able to redrive messages using the permissions you configured using the AWS console only in the regions where you have previously used the DLQ redrive. For example, say you had "Account A" in both us-east-1 and eu-west-1. "Account A" was used to redrive messages on the AWS console in us-east-1 prior to June 8, 2023, but not in eu-west-1. Between June 8, 2023 and August 31, 2023, if "Account A’s" policy permissions don't match one of the options above, it can only be used to redrive messages on the AWS console in us-east-1, and not in eu-west-1. Important If your DLQ redrive permissions do not match one of these options after August 31, 2023, your account will no longer be able to redrive DLQ messages using the AWS console. However, if you used the DLQ redrive feature on the AWS Console during August 2023, you have an extension until October 15, 2023 to adopt the new permissions according to one of these options. For more information, see the section called “Identifying impacted policies”. The following are queue permission examples for each DLQ redrive option. When using server-side encrypted (SSE) queues, the corresponding AWS KMS key permission is required. CloudTrail update and permission requirements 69 Developer Guide Amazon Simple Queue Service Action-based { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes", "sqs:StartMessageMoveTask", "sqs:ListMessageMoveTasks", "sqs:CancelMessageMoveTask" ], "Resource": "arn:aws:sqs:<DLQ_region>:<DLQ_accountId>:<DLQ_name>" }, { "Effect": "Allow", "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:<DestQueue_region>:<DestQueue_accountId>:<DestQueue_name>" } ] } Managed policy The following managed policies contain the required updated permissions: • AmazonSQSFullAccess – Includes the following dead-letter queue redrive tasks: start, cancel, and list. • AmazonSQSReadOnlyAccess – Provides read-only access, and includes the list dead-letter queue redrive task. CloudTrail update and permission requirements 70 Amazon Simple Queue Service Developer Guide Permission Policy that uses sqs* wildcard { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "sqs:*", "Resource": "*" } ] } Identifying impacted policies If you are using customer managed policies (CMPs), you can use AWS CloudTrail and IAM to identify the policies impacted by the queue permissions update. CloudTrail update and permission requirements 71 Amazon Simple Queue Service Developer Guide Note If you are using AmazonSQSFullAccess and AmazonSQSReadOnlyAccess, no further action is required. 1. Sign in to the AWS CloudTrail console. 2. On the Event history page, under Look up attributes, use the drop down menu to select Event name. Then, search for CreateMoveTask. 3. Choose an event to open the Details page. In the Event records section, retrieve the UserName or RoleName from the userIdentity ARN. 4. Sign into IAM console. • For users, choose Users. Select the user with the UserName identified in the previous step. • For roles, choose Roles. Search for the user with the RoleName identified in the previous step. 5. On the Details page, in the Permissions section, review any policies with the sqs: prefix in Action, or review policies that have Amazon SQS queue defined in Resource. Creating alarms for dead-letter queues using Amazon CloudWatch Set up a CloudWatch alarm to monitor messages in a dead-letter queue using the ApproximateNumberOfMessagesVisible metric. For detailed instructions, see Creating CloudWatch alarms for Amazon SQS metrics. When the alarm triggers, indicating messages have been moved to the dead-letter queue, you can poll the queue to review and retrieve them. Message metadata for Amazon SQS Use message attributes to add custom metadata to Amazon SQS messages for your applications. Use message system attributes to store metadata for integration with other AWS services, such as AWS X-Ray. Amazon SQS message attributes Amazon SQS allows you to include structured metadata (such as timestamps, geospatial data, signatures, and identifiers) with messages using message attributes. Each message can have up Creating alarms for dead-letter queues using Amazon CloudWatch 72 Amazon Simple Queue Service Developer Guide to 10 attributes. Message attributes are optional and separate from the message body (however, they are sent alongside it). Your consumer
sqs-dg-028
sqs-dg.pdf
28
for Amazon SQS Use message attributes to add custom metadata to Amazon SQS messages for your applications. Use message system attributes to store metadata for integration with other AWS services, such as AWS X-Ray. Amazon SQS message attributes Amazon SQS allows you to include structured metadata (such as timestamps, geospatial data, signatures, and identifiers) with messages using message attributes. Each message can have up Creating alarms for dead-letter queues using Amazon CloudWatch 72 Amazon Simple Queue Service Developer Guide to 10 attributes. Message attributes are optional and separate from the message body (however, they are sent alongside it). Your consumer can use message attributes to handle a message in a particular way without having to process the message body first. For information about sending messages with attributes using the Amazon SQS console, see Sending a message with attributes using Amazon SQS. Note Don't confuse message attributes with message system attributes: Whereas you can use message attributes to attach custom metadata to Amazon SQS messages for your applications, you can use message system attributes to store metadata for other AWS services, such as AWS X-Ray. Topics • Message attribute components • Message attribute data types • Calculating the MD5 message digest for message attributes Message attribute components Important All components of a message attribute are included in the 256 KB message size restriction. The Name, Type, Value, and the message body must not be empty or null. Each message attribute consists of the following components: • Name – The message attribute name can contain the following characters: A-Z, a-z, 0-9, underscore (_), hyphen (-), and period (.). The following restrictions apply: • Can be up to 256 characters long • Can't start with AWS. or Amazon. (or any casing variations) • Is case-sensitive • Must be unique among all attribute names for the message • Must not start or end with a period Message attributes 73 Amazon Simple Queue Service Developer Guide • Must not have periods in a sequence • Type – The message attribute data type. Supported types include String, Number, and Binary. You can also add custom information for any data type. The data type has the same restrictions as the message body (for more information, see SendMessage in the Amazon Simple Queue Service API Reference). In addition, the following restrictions apply: • Can be up to 256 characters long • Is case-sensitive • Value – The message attribute value. For String data types, the attribute values has the same restrictions as the message body. Message attribute data types Message attribute data types instruct Amazon SQS how to handle the corresponding message attribute values. For example, if the type is Number, Amazon SQS validates numerical values. Amazon SQS supports the logical data types String, Number, and Binary with optional custom data type labels with the format .custom-data-type • String – String attributes can store Unicode text using any valid XML characters. • Number – Number attributes can store positive or negative numerical values. A number can have up to 38 digits of precision, and it can be between 10^-128 and 10^+126. Note Amazon SQS removes leading and trailing zeroes. • Binary – Binary attributes can store any binary data such as compressed data, encrypted data, or images. • Custom – To create a custom data type, append a custom-type label to any data type. For example: • Number.byte, Number.short, Number.int, and Number.float can help distinguish between number types. • Binary.gif and Binary.png can help distinguish between file types. Message attributes 74 Amazon Simple Queue Service Developer Guide Note Amazon SQS doesn't interpret, validate, or use the appended data. The custom-type label has the same restrictions as the message body. Calculating the MD5 message digest for message attributes If you use the AWS SDK for Java, you can skip this section. The MessageMD5ChecksumHandler class of the SDK for Java supports MD5 message digests for Amazon SQS message attributes. If you use either the Query API or one of the AWS SDKs that doesn't support MD5 message digests for Amazon SQS message attributes, you must use the following guidelines to perform the MD5 message digest calculation. Note Always include custom data type suffixes in the MD5 message-digest calculation. Overview The following is an overview of the MD5 message digest calculation algorithm: 1. 2. Sort all message attributes by name in ascending order. Encode the individual parts of each attribute (Name, Type, and Value) into a buffer. 3. Compute the message digest of the entire buffer. The following diagram shows the encoding of the MD5 message digest for a single message attribute: Message attributes 75 Amazon Simple Queue Service Developer Guide To encode a single Amazon SQS message attribute 1. 2. 3. Encode the name: the length (4 bytes) and the UTF-8 bytes of the name. Encode the data type: the
sqs-dg-029
sqs-dg.pdf
29
following is an overview of the MD5 message digest calculation algorithm: 1. 2. Sort all message attributes by name in ascending order. Encode the individual parts of each attribute (Name, Type, and Value) into a buffer. 3. Compute the message digest of the entire buffer. The following diagram shows the encoding of the MD5 message digest for a single message attribute: Message attributes 75 Amazon Simple Queue Service Developer Guide To encode a single Amazon SQS message attribute 1. 2. 3. Encode the name: the length (4 bytes) and the UTF-8 bytes of the name. Encode the data type: the length (4 bytes) and the UTF-8 bytes of the data type. Encode the transport type (String or Binary) of the value (1 byte). Note The logical data types String and Number use the String transport type. The logical data type Binary uses the Binary transport type. a. b. For the String transport type, encode 1. For the Binary transport type, encode 2. 4. Encode the attribute value. a. b. For the String transport type, encode the attribute value: the length (4 bytes) and the UTF-8 bytes of the value. For the Binary transport type, encode the attribute value: the length (4 bytes) and the raw bytes of the value. Message attributes 76 Amazon Simple Queue Service Developer Guide Amazon SQS message system attributes Whereas you can use message attributes to attach custom metadata to Amazon SQS messages for your applications, you can use message system attributes to store metadata for other AWS services, such as AWS X-Ray. For more information, see the MessageSystemAttribute request parameter of the SendMessage and SendMessageBatch API actions, the AWSTraceHeader attribute of the ReceiveMessage API action, and the MessageSystemAttributeValue data type in the Amazon Simple Queue Service API Reference. Message system attributes are structured exactly like message attributes, with the following exceptions: • Currently, the only supported message system attribute is AWSTraceHeader. Its type must be String and its value must be a correctly formatted AWS X-Ray trace header string. • The size of a message system attribute doesn't count towards the total size of a message. Resources required to process Amazon SQS messages Amazon SQS provides estimates of the approximate number of delayed, visible, and not visible messages in a queue to help you assess the resources needed for processing. For more information about visibility, see Amazon SQS visibility timeout. Note For some metrics, the result is approximate because of the distributed architecture of Amazon SQS. In most cases, the count should be close to the actual number of messages in the queue. The following table lists the attribute name to use with the GetQueueAttributes action: Task Attribute name Get the approximate number of messages available for retrieval from the queue. ApproximateNumberOfMessages Visible Get the approximate number of messages in the queue that are delayed and not available ApproximateNumberOfMessages Delayed Message system attributes 77 Amazon Simple Queue Service Developer Guide Task Attribute name for reading immediately. This can happen when the queue is configured as a delay queue or when a message has been sent with a delay parameter. Get the approximate number of messages that are in flight. Messages are considered to be in flight if they have been sent to a client but have not yet been deleted or have not yet reached the end of their visibility window. ApproximateNumberOfMessages NotVisible Amazon SQS list queue pagination The listQueues and listDeadLetterQueues API methods support optional pagination controls. By default, these API methods return up to 1000 queues in the response message. You can set the MaxResults parameter to return fewer results in each response. Set parameter MaxResults in the listQueues or listDeadLetterQueues request to specify the maximum number of results to be returned in the response. If you do not set MaxResults, the response includes a maximum of 1,000 results and the NextToken value in the response is null. If you set MaxResults, the response includes a value for NextToken if there are additional results to display. Use NextToken as a parameter in your next request to listQueues to receive the next page of results. If there are no additional results to display, the NextToken value in the response is null. Amazon SQS cost allocation tags To organize and identify your Amazon SQS queues for cost allocation, you can add metadata tags that identify a queue's purpose, owner, or environment. This is especially useful when you have many queues. To configure tags using the Amazon SQS console, see the section called “Configuring tags for a queue” You can use cost allocation tags to organize your AWS bill to reflect your own cost structure. To do this, sign up to get your AWS account bill to include tag keys and values. For more information, see Setting Up a Monthly Cost Allocation Report in the AWS