Highly Available Order Service With Durable Async Jobs
System DesignModel answerLast updated
Design a horizontally scalable Spring Boot order backend that survives deploys and traffic spikes while guaranteeing that invoice and email jobs are never lost.
Scenario
Your team runs an order-processing backend built with Spring Boot. At peak it must absorb about 5,000 requests per second. Each new order also triggers slow follow-up work, such as rendering a PDF invoice and sending one or more confirmation emails.
The service has to stay up while new versions are released, cope with sudden bursts of traffic, and never silently drop a follow-up job, even if a server dies halfway through one.
What your design must cover
- Statelessness and scaling. Make the application tier horizontally scalable behind a load balancer.
- Authentication state. Explain how a logged-in user is recognised no matter which instance handles the request.
- Offloading slow work. Describe how long-running jobs leave the request-response path.
- Crash safety. Show how jobs survive the failure of an instance in the middle of processing.
- Zero-downtime releases. Explain how you ship a new version without cutting off in-flight requests.
Expected deliverables
- A high-level description or diagram of the path between the client, load balancer, Spring Boot instances, database, and job queue.
- The specific technologies or Spring features you would use for shared authentication state and for asynchronous messaging.
- A comparison of queueing approaches, for example a durable message broker versus a database table that workers poll, with the trade-offs of each.
State your assumptions about traffic mix, latency targets, and job cost, and use them to size the system.
Hints
Hint 1
Convert the headline number into capacity: how many API instances and how many CPU-seconds of invoice rendering per second? That should show the web tier and the job workers need to scale separately.
Hint 2
There are three distinct ways to lose a job: the app crashes between saving the order and publishing the message, the broker loses the message, and a worker dies mid-task. Match each failure with its own remedy.
Hint 3
Because retries and redelivery produce at-least-once delivery, think about what makes a consumer safe to run twice on the same message, and what you do with messages that keep failing.
Hint 4
For deployments, think about readiness probes, connection draining, graceful shutdown, and keeping database schema changes compatible with both the old and new application versions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions and sizing
State the numbers first; they drive every later decision.
| Assumption | Value |
|---|---|
| Peak load | 5,000 RPS, spikes to about 3x (15,000 RPS) |
| Mix | ~90% reads, ~10% writes (about 500 orders/s) |
| Latency target | p99 under 200 ms for synchronous endpoints |
| Per-order background work | 1 PDF (~1.5 s CPU), 1-2 emails (~100-300 ms, I/O bound) |
| Durability | No job may be lost; late is acceptable |
Derived sizing:
- API tier: a 2 vCPU instance handles roughly 600-800 RPS, so about 8 instances at baseline. Add N+2 headroom: run 10 minimum, autoscale toward 30.
- PDF workers: 500/s x 1.5 s is about 750 CPU-seconds of work per second, so hundreds of cores at peak. That alone justifies a separate worker pool that never shares threads with the web tier.
- Email workers: about 1,000 emails/s, I/O bound, so a small pool with high concurrency.
2. API shape
POST /orderswith anIdempotency-Keyheader returns202 Acceptedwith{orderId, status: PENDING}.GET /orders/{id}returns status and an invoice link once ready.- Invoice download redirects to a pre-signed object-storage URL.
Returning 202 keeps the request path fast. The client polls or receives a push/webhook when the invoice is ready.
3. Architecture
Client -> CDN/WAF -> L7 load balancer
-> Spring Boot API instances (stateless, multi-AZ, 10..30)
|- Redis (token denylist / sessions, rate limits)
|- PostgreSQL primary + replicas (orders + outbox in one TX)
'- Outbox relay (Debezium CDC or SKIP LOCKED poller)
-> Broker (Kafka or RabbitMQ, replicated)
-> invoice workers -> object storage
-> email workers -> email provider
-> retry topics / DLQ
Stateless API tier. No in-memory sessions, no local file writes, no @Scheduled job that assumes a single instance (use a lock or move it to a worker). Config from environment or a config server. Spread across availability zones; round-robin or least-connections, no sticky sessions.
Authentication state. Two valid options:
- Spring Session + Redis:
HttpSessionlives in Redis, any instance serves any request, and logout/revocation is just deleting a key. Cost: a Redis hop on every request and a hard dependency. - Stateless JWT (Spring Security OAuth2 Resource Server): each instance validates the signature locally. Use short-lived access tokens (5-15 min) plus refresh tokens, and a small Redis denylist for revocation.
At this volume, JWT is the better default; choose Redis sessions for server-rendered or legacy apps that need instant revocation.
4. Never losing a background job
Each loss mode needs its own fix.
a) Dual-write gap. Saving the order and then publishing to the broker are two separate operations; a crash between them loses the job. Use the transactional outbox: write the order and an outbox row in the same database transaction. A relay (Debezium CDC preferred, or a poller using SELECT ... FOR UPDATE SKIP LOCKED) publishes outbox rows and marks them sent. Never publish from inside @Transactional and hope.
b) Broker loss. Configure durability:
- Kafka: replication factor 3,
min.insync.replicas=2, produceracks=all, idempotent producer. - RabbitMQ: quorum queues, persistent messages, publisher confirms.
c) Worker crash mid-task. Acknowledge only after the work finishes. RabbitMQ: manual ack, so unacked messages are redelivered when the channel closes. Kafka: commit offsets after processing; a crash causes partition reassignment and reprocessing. Retry with exponential backoff (DefaultErrorHandler, @RetryableTopic, or RabbitMQ DLX with TTL). After N attempts send to a dead-letter queue with an alert and a replay tool.
This gives at-least-once delivery, so consumers must be idempotent: keep a processed_tasks(task_id PK) table, or use deterministic output keys (the invoice path is derived from the order ID, so a rerun overwrites rather than duplicates). For email, record a send marker before or with the provider call and pass a provider idempotency key where supported.
@Async with a ThreadPoolTaskExecutor is acceptable only for best-effort work such as cache warming, because its queue is in memory and dies with the instance.
5. Queueing trade-offs
| Option | Strengths | Weaknesses | Best fit |
|---|---|---|---|
| Kafka | Huge throughput, replayable log, multiple consumers per event, lag is a clean autoscaling signal | Per-message retry/delay awkward, parallelism capped by partitions, operationally heavy | One OrderCreated event feeding invoice, email, analytics |
| RabbitMQ | Per-message ack, DLX/TTL, priorities, flexible routing | Lower ceiling, no replay after ack, big backlogs hurt | Task queues with varied retry rules |
DB polling (SKIP LOCKED, JobRunr, db-scheduler) | No new infrastructure, transactional with business data | Polling latency and load, DB becomes bottleneck, index bloat | Low-to-moderate volume, or as the outbox stage |
| Managed (SQS) | No operations, visibility timeout handles crashes | Lock-in, payload limit, FIFO throughput limits | Cloud-native teams |
Recommendation: Postgres outbox, then Kafka, then a consumer group per task type. The database provides atomicity; the broker provides fan-out and throughput. At around 500 jobs/s, pure DB polling would be a risk during spikes.
6. Handling spikes
- Autoscale API instances on CPU or RPS, and workers on consumer lag.
- The queue absorbs bursts: invoices lag but nothing is dropped.
- Rate-limit per client, apply backpressure with bounded thread pools, and add circuit breakers (Resilience4j) around the email provider.
- Cache hot reads and send status reads to replicas.
7. Zero-downtime deployment
- Rolling or blue-green release behind the load balancer, with
maxUnavailable=0andmaxSurgeabove zero. - Readiness probes gate traffic; liveness probes are kept separate and lenient.
- Graceful shutdown:
server.shutdown=gracefulwith aspring.lifecycle.timeout-per-shutdown-phase, plus a preStop delay so the load balancer deregisters the instance before it stops accepting requests. - Workers: stop polling, finish or release the current message, then exit. Unacked work is redelivered safely thanks to idempotency.
- Schema changes: use expand/contract migrations so old and new versions both work against the database during rollout.
- Optionally canary a small percentage of traffic first and roll back automatically on error-rate regression.
8. Common mistakes
- Publishing to the broker inside the transaction and assuming atomicity.
- Using
@Asyncor an in-memory queue for critical work. - Auto-acknowledging before processing completes.
- Forgetting idempotency despite at-least-once delivery.
- Sticky sessions or local session state.
- Running PDF rendering on web threads.
- Breaking schema changes that fail the old version mid-rollout.
- No DLQ or alerting for poison messages.