SQS 短轮询是否比长轮询更可取?

Is SQS short polling ever preferable to long polling?

Amazon SQS 支持两种可用消息轮询模式:短轮询和长轮询。使用长轮询,消费者指定 1-20 秒的超时时间以等待可用消息。

根据documentation

By default, Amazon SQS uses short polling, querying only a subset of its servers (based on a weighted random distribution), to determine whether any messages are available for a response.

Long polling offers the following benefits:

  • Eliminate empty responses by allowing Amazon SQS to wait until a message is available in a queue before sending a response. Unless the connection times out, the response to the ReceiveMessage request contains at least one of the available messages, up to the maximum number of messages specified in the ReceiveMessage action.
  • Eliminate false empty responses by querying all—rather than a subset of—Amazon SQS servers.
  • Return messages as soon as they become available.

以上特点让long polling看起来很不错。那么有没有更适合短轮询的用例?

特别是对于高吞吐量队列,短轮询是否比长轮询快?

长轮询几乎总是优于短轮询。以下是可能需要短轮询的两个用例(在 SQS 常见问题解答中给出):

  • 当需要立即处理消息时。
  • 当您在单个线程中轮询多个队列时。

来自 SQS FAQs:

In almost all cases, Amazon SQS long polling is preferable to short polling. Long-polling requests let your queue consumers receive messages as soon as they arrive in your queue while reducing the number of empty ReceiveMessageResponse instances returned.

Amazon SQS long polling results in higher performance at reduced cost in the majority of use cases. However, if your application expects an immediate response from a ReceiveMessage call, you might not be able to take advantage of long polling without some modifications to your application.

For example, if your application uses a single thread to poll multiple queues, switching from short polling to long polling will probably not work, because the single thread will wait for the long-poll timeout on any empty queues, delaying the processing of any queues that might contain messages.

In such an application, it is a good practice to use a single thread to process only one queue, allowing the application to take advantage of the benefits that Amazon SQS long polling provides.