A shared asynchronous pipeline has an awkward failure mode: one customer starts a large import, and everyone else’s work waits behind it. Adding fairness to dispatch helps, but it does not solve downstream overload or recover requests that never return a result.
We ran into both problems in an event-driven classification workflow. The eventual solution combined Amazon SQS fair queues, a durable record of in-progress work, completion-driven message deletion, and partial admission control. The rollout also exposed the need for a separate, explicit downstream concurrency budget. The important design choice was not the queue itself. It was keeping a message in flight until the downstream business operation had actually finished—while acknowledging that SQS’s in-flight quota is not a safe application-level concurrency limit.
The problem: fairness at dispatch is not enough
The original flow consumed changes from a stream, populated database records, and inserted work into a database-backed journal. An orchestrator polled the journal and published requests to an external classifier. A separate result consumer eventually applied the classification.
That design created three problems:
- Noisy neighbours: a tenant running a large import occupied a disproportionate share of dispatch capacity. The journal could rotate tenants, but the classifier still received work faster than it could finish it.
- Unbounded downstream pressure: dispatch was not tied to actual completion. Requests could accumulate downstream even while the journal appeared healthy.
- Unrecoverable missing results: once a request had been published, a missing downstream response was not automatically retried. Tracking a loss is not the same as recovering from it.
The ingestion path also performed multiple placeholder and journal writes per event, while orchestrators repeatedly polled database tables. We were using the database as both a persistence layer and a distributed work scheduler.
The architecture we chose
The replacement routes stream events through an EventBridge Pipe into an SQS standard queue, with the tenant identifier set as MessageGroupId. Unlike a FIFO queue, an SQS fair queue does not enforce ordering within a group. It detects tenants consuming disproportionate processing capacity and preferentially serves quieter groups.
The simplified workflow is:
Event stream
│
▼
EventBridge Pipe ─────────► Pipe failure DLQ
│
▼
SQS standard queue (MessageGroupId = tenant)
│
▼
Stateless consumers
│
├── No downstream work needed ─────► Delete message
│
├── Equivalent request in progress ► Coalesce + delete
│
└── New downstream request
│
▼
Durable hold record
│
▼
Publish to classifier
│
▼
Wait for result, keeping
SQS message in flight
│
▼
Apply result + release hold
│
▼
Delete SQS message
Visibility expiry ─► Redelivery / retry ─► DLQ on exhaustion
Every event enters the same queue. The consumers must read the current authoritative state before deciding whether classification is necessary, so routing only ‘expensive’ events at the stream boundary would require duplicating domain logic upstream.
Why the message stays in flight
Amazon SQS considers a message in flight after a consumer receives it and before it is deleted or its visibility timeout expires. That state matters for fairness: deleting the message immediately after publishing a classification request would make slow or overloaded tenants appear cheaper than they really are.
Instead, we persist a hold record containing a reference to the resource, a request fingerprint, the current SQS receipt handle, and the delivery attempt. The consumer publishes the request, adjusts visibility for the expected completion window, and returns. It does not keep a thread or actor blocked while waiting.
When any worker processes the result, it can find the corresponding hold and delete the SQS message using the saved receipt handle. The operation is idempotent: completion, redelivery, and a stale receipt handle may race, so neither a database hold nor an acknowledgement should be treated as exactly-once execution.
Crucially, the hold is created before publishing. Otherwise a fast classifier response could arrive before there was anything to release.
Three outcomes per event
| Outcome | Consumer action | Queue action |
|---|---|---|
| Already complete | Apply any local changes; no classification required | Delete |
| Equivalent request active | Coalesce against an existing request fingerprint | Delete duplicate |
| New classification needed | Persist hold, publish, wait for result | Keep in flight |
Coalescing matters for capacity planning. Several item changes may lead to the same product-level classification. Holding every duplicate would make SQS’s in-flight count represent event volume rather than actual downstream work. A database uniqueness constraint on the resource and fingerprint makes the coalescing decision safe under concurrent consumers.
Fairness is not admission control
SQS fair queues help decide whose work to return next. They do not impose a tenant-specific rate limit or guarantee that your downstream system can sustain the offered throughput.
An approximate capacity model is:
Sustainable throughput ≈ average in-flight requests / average completion time
For illustration, 30,000 concurrent requests with an average 10-minute completion time represent roughly 3,000 completions per minute in steady state. Those are example values, not production measurements.
SQS standard queues have a default in-flight quota of approximately 120,000 messages, subject to AWS quota configuration. This is a ceiling on concurrently received but undeleted messages, not an appropriate downstream rate limit by itself. If the classifier’s safe concurrency is lower, you need a separate admission-control budget.
Long polling adds a subtle complication: once the in-flight quota is reached, an empty receive can look like an empty queue. We used adaptive polling with short, jittered waits after empty receives rather than a cluster-wide counter. This reduced coordination overhead, but it deliberately did not solve the separate problem of limiting classifier load below the SQS quota.
Retries, failures, and completion races
A visibility timeout turns an unanswered request into another delivery attempt. On redelivery, the consumer reloads the authoritative state, refreshes the receipt handle, and decides whether to republish. After a configured receive budget, SQS redrives the message to a dead-letter queue, where it can be investigated and replayed.
The queue itself is not a transactional outbox. Persisting a hold, publishing downstream, applying the result, and deleting the SQS message span different systems. We therefore designed for duplicate publication and repeated completion rather than claiming exactly-once delivery.
Three failure modes deserve special attention:
Publish failures. If the downstream broker is unavailable, a circuit breaker pauses new receives. Already received messages can be given a short retry window. Deleting or incorrectly clearing the hold can accidentally turn a failed publish into a permanently skipped request.
Ambiguous results. If the classifier returns only the resource identifier, it cannot distinguish which request attempt produced the result. The clean solution is an end-to-end attempt or correlation token. Without one, completion logic must conservatively handle multiple outstanding attempts.
Retry amplification. When the downstream backlog is longer than the visibility timeout, already-published work can be published again. Under load, the retry mechanism can make an overloaded dependency more overloaded. An adaptive timeout, explicit attempt reconciliation, or a smaller admission-control budget may be necessary.
We also added separate dead-letter monitoring for ingestion-pipe failures and consumer retries. They represent different failure domains and require different recovery procedures.
Migrating without losing events
The rollout was incremental rather than a single cutover:
- Extract the existing ingestion and publication logic behind reusable services.
- Deploy the new queue, hold schema, consumers, and monitors without admitting production tenants.
- Run the receive/parse/delete path in shadow mode.
- Enable the new consumer for a small tenant cohort while keeping the original path active.
- Only then disable the old path for those tenants; widen the cohort after validation.
- Retain rollback switches until results from the old path have drained.
The order of the two per-tenant flags matters. Enabling the new path before disabling the old one creates a brief, safe overlap, provided state changes are idempotent. Reversing that order creates a gap where an event can be missed.
During overlap, the old journal must also recognise work already represented by a live hold. Otherwise both paths can publish the same request independently.
Concurrent processing exposed database uniqueness races that had been rare on the old serialised path. That is an important migration lesson: changing the queue often changes your write concurrency as much as your messaging semantics.
What improved — and what did not
We compared two similarly sized multi-day observation windows before and after cutover. The newer period handled about 10% more incoming events, so per-event figures provide a more useful comparison than raw database totals. These are observational windows, not a controlled experiment: workload mix and concurrent changes may also explain part of the movement. The figures below are rounded or relative, with dates, customer volumes and internal telemetry identifiers omitted.
| Indicator | Observed change |
|---|---|
| Database rows written per incoming event | 13% lower |
| Peak writer CPU utilisation | 41 percentage points lower |
| Average writer CPU utilisation | Essentially unchanged despite higher traffic |
| Average classification p95 latency | 8% lower |
| Classification results per published request | 0.7 percentage points higher |
| Database statements per event | 8% higher |
| Legacy journal batches | 18% higher |
The database improvement is real, but incomplete. Eliminating placeholder, metadata and item-request journal writes reduced write amplification. Peak CPU also flattened substantially. However, the old journal still processes other event types and continues polling, while the new hold records introduce their own reads and writes. Total database statement volume actually increased after normalising for traffic. We should not claim that the migration removed database polling or reduced query load across the whole system.
Normal-load latency barely changed. Classification p95 stayed in the same broad single-digit-minute range. That makes sense: fairness is most valuable when a noisy tenant saturates a shared dependency, not when the classifier already has spare capacity.
What happened during a burst
A separate stress test drove tens of millions of events in a day and created a seven-figure visible queue backlog. The important measurements were not the raw volumes but the way the system behaved:
- Concurrent in-flight work remained below the configured SQS quota, rather than allowing every queued event to become downstream work.
- The busiest hour’s classification p95 remained under 25 minutes.
- The visible backlog fell by more than 99% within approximately two hours of the peak.
Under the earlier architecture, a different overload episode had driven classification p95 beyond two hours. That is useful directional evidence, not a like-for-like benchmark: the traffic mix, burst shape and environment may have differed.
The burst also exposed the cost of our fixed hold timeout. Some downstream operations were still pending when their SQS messages became visible again, triggering tens of thousands of duplicate publishes. The retry mechanism prevented silent loss but amplified load at the least convenient moment.
Reliability and operational behaviour
In the first rollout period, more than 99% of held requests were released following a result. Redeliveries were a small fraction of held messages, concentrated heavily around the stress test. A much smaller set exhausted its retry budget and reached a monitored dead-letter queue.
The publish circuit breaker also opened during a temporary broker disruption and recovered without manual intervention. This demonstrated the value of stopping new admission instead of repeatedly sending work to an unhealthy dependency.
These observations should not be interpreted as an exact recovery rate: counts of published requests, accepted results, retries and held messages represent different stages and time windows. In particular, a retried request is not necessarily a request that would have been permanently lost in the old system.
The remaining work is clear: prevent retries from amplifying an existing backlog, make every valid business-completion path release its hold, add end-to-end attempt correlation, and finally remove the legacy journal and polling infrastructure once its remaining workloads have migrated.
Lessons worth reusing
Define completion at the business boundary. A successful publish does not mean the operation succeeded. Delete only when the outcome you care about is durable.
Fairness and admission control solve different problems. Tenant-aware scheduling reduces noisy-neighbour interference; it does not replace a downstream capacity budget.
Make idempotency part of the design, not a retry patch. The event stream, SQS, database, broker, and classifier all introduce opportunities for replay or concurrent execution.
Measure retries as load, not just reliability. A retry strategy that works during ordinary failures may amplify a prolonged backlog.
Prefer gradual cutovers with deliberate overlap. A small window of duplicate processing is generally easier to recover from than a window of missing events.
The final design is not ‘SQS replaces a database journal’. It is a change in ownership: the queue owns delivery and fairness, a durable hold links delivery to asynchronous completion, and the application owns idempotency and downstream backpressure.
