Building a Concurrent Rendering Pipeline for Placeholder Substitution
System DesignModel answerLast updated
Design a horizontally scalable backend that renders millions of placeholder-substitution jobs per hour using queues and worker pools, with fault tolerance, backpressure, and sensible job routing.
Imagine you already have a routine that takes a template such as server={{db_host}}:{{db_port}} and a dictionary of values, and returns the text with every placeholder filled in. You now need to offer this as a production backend service that handles millions of rendering jobs per hour.
Each job contains:
- a unique identifier,
- one template string (or a small group of them),
- a dictionary of values to substitute.
The service must sustain high throughput, scale out horizontally, keep slow or oversized jobs from holding up everything else, and use a worker pool to run jobs concurrently.
Walk through a design that covers the following.
- Overall architecture. Name the main components (entry API, queue, workers, storage) and explain how a job moves through them.
- Worker pool mechanics. Explain how jobs enter the system (producers) and how workers pick them up (consumers). Show how this is the producer–consumer pattern and how you bound concurrency so the system is not overloaded.
- Distributing work. Compare ways to assign jobs to workers: round-robin, random, a single shared queue, several queues, and hashing on a key. Explain when hash-based assignment (for example by customer or resource) is worth it, and the trade-offs among fairness, load balance, and ordering of related jobs.
- Scalability and reliability. Describe how the system scales as volume grows, how it recovers when a worker dies mid-job (retries, idempotency), and how it pushes back on producers that send too much.
- Implementation choices. Suggest queue technology and justify it, list the metrics you would monitor, and mention optimizations specific to template rendering (such as caching parsed templates or batching).
Give a step-by-step design and be explicit about the trade-offs behind each decision.
Hints
Hint 1
Start with numbers: convert jobs per hour to jobs per second, estimate payload size, and note that a single-pass substitution is cheap. The real risks are I/O, serialization, and a few huge jobs, which should shape the design.
Hint 2
Think about two levels of producer–consumer: the broker between API servers and workers, and a bounded in-memory buffer between a worker's fetcher and its executor threads or processes. Bounded buffers are where backpressure comes from.
Hint 3
For distribution, ask what property you need: ordering, cache locality, or isolation justifies hashing on a key; pure throughput favors a shared competing-consumer queue. Then consider hot keys and head-of-line blocking, and separate lanes for small and large jobs.
Hint 4
For failures, decide when to acknowledge or commit (after the result is durably written) and why deterministic rendering makes at-least-once delivery safe when paired with idempotent result writes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify requirements and size the problem
Ask first, then draw.
Functional
- Submit a job (
job_id, templates, values) and later fetch the output by polling or callback. - Decide the missing-key policy: fail the job, leave the placeholder untouched, or use a default.
Non-functional
- High throughput, horizontal scale.
- Slow jobs must not delay fast ones.
- At-least-once processing with idempotent results.
Rough numbers
- 10M jobs/hour is about 2,800 jobs/s on average. Plan for around 10k/s at peak.
- At roughly 3 KB per job, peak ingress is about 30 MB/s.
- A single-pass substitution over a few KB costs tens of microseconds, so one core can do tens of thousands of small jobs per second.
Conclusion: CPU is cheap; the dangers are I/O, serialization, and heavy-tailed sizes. One 50 MB template or a dictionary with 100k keys is what actually stalls a worker. This drives lane separation and hard limits.
2. API and data model
POST /jobsreturns202with ajob_id; a batch endpoint accepts up to about 1,000 jobs.GET /jobs/{id}returns status and output (or a reference to it).- A job record (in a key-value store keyed by
job_id) holds tenant, status (QUEUED, RUNNING, DONE, FAILED), attempt count, size, payload and result references, and timestamps. - Claim-check pattern: payloads above roughly 256 KB go to object storage; the queue message only carries a pointer. This keeps the broker fast.
- Client-supplied job IDs make submission itself idempotent.
3. Architecture
Clients -> LB -> stateless API (auth, quota, validate, size-classify)
|- small jobs -> topic jobs.small (partitioned by tenant)
|- large jobs -> object store + topic jobs.large
Worker pools (one per lane, autoscaled) -> render -> result store -> status/callback
Failed jobs -> retry topics (delayed) -> dead-letter queue
In-process LRU cache of parsed templates
The API enforces per-tenant token-bucket quotas and rejects oversized input. The queue is the durable buffer decoupling producers from consumers. Workers are stateless.
4. Worker pool as producer–consumer
Producers are the API servers. They publish in small batches (a few ms of linger) with full-replica acknowledgment, and return 202 only after the broker confirms.
Consumers run three stages inside each worker process:
- A fetcher polls the broker and pushes into a bounded in-memory queue (for example 2x the executor count). When it fills, the fetcher blocks, so the worker stops pulling. That is backpressure.
- An executor pool renders jobs. For CPU-bound work in a GIL language use processes (about one per core); use async I/O for fetching payloads and writing results.
- A committer commits the highest contiguous completed offset per partition.
This is producer–consumer twice: the broker between API and workers, and the bounded queue between fetcher and executors.
Concurrency limits
- Fixed executor count plus a semaphore on in-flight jobs.
- A per-tenant in-flight cap so one tenant cannot occupy every executor.
- Per-job timeouts (for example 2 s for small, 60 s for large). Process pools make killing a stuck job easy.
- Hard caps on template size, placeholder count, and output size.
5. Distributing work
| Strategy | Pros | Cons |
|---|---|---|
| Shared queue, competing consumers | Best natural balance; idle workers pull | No ordering or locality |
| Round-robin / random push | Simple | Ignores job cost; slow worker builds backlog |
| Hash by key to partitions | Ordering, cache locality, isolation | Hot keys, skew, rebalancing |
| Multiple queues by class | Avoids head-of-line blocking, supports SLAs | More to operate |
Choose hashing when related jobs need ordering (successive renders for one resource), locality (a tenant reuses templates, so the parsed-template cache hits), or isolation (per-tenant rate limiting is simpler). With Kafka, partition = hash(key) % P, with P chosen generously (for example 256) so consumers can scale to P without repartitioning.
Trade-offs
- Hashing trades load balance for ordering and locality.
- Mitigate hot tenants by salting the key (ordering then holds per sub-key only) or giving big tenants a dedicated lane.
- Hash on the finest key that needs ordering (resource rather than tenant) for better spread.
- A slow job blocks its partition. Process different keys concurrently within a partition, keep same-key jobs serial, and commit contiguous offsets. Size-based lanes help too.
- If no ordering is required, use a shared queue.
6. Scalability and reliability
Scaling
- API and workers are stateless; autoscale on consumer lag and buffer occupancy rather than CPU alone.
- Partition count caps consumer parallelism, so over-provision it.
- At very large scale, shard by region or tenant tier. The result store is a partitioned KV keyed by
job_id.
Failures
- Write the result, then ack or commit. A crash mid-job leads to redelivery (at-least-once).
- Idempotency: rendering is deterministic, so a retry yields the same output; writing results keyed by
job_idmakes duplicates harmless. - Retries with exponential backoff via delayed retry topics (for example 5 s, 1 m, 10 m), then a dead-letter queue with alerting. Do not retry permanent errors such as a missing key under a fail policy.
- Poison messages are bounded by attempt count and timeouts.
Backpressure
- Bounded worker buffers stop pulling when full, so lag grows in the broker rather than in worker memory.
- The API applies per-tenant quotas and returns
429withRetry-After; if global lag passes a threshold, shed or throttle low-priority tenants.
7. Technology and optimizations
- Queue: Kafka for high throughput, partition ordering, and replay; SQS or RabbitMQ if per-message acks, delays, and simpler operation matter more than ordering.
- Storage: object store for large payloads, a KV store for job state.
- Metrics: queue depth and consumer lag, worker utilization, job latency (p50/p95/p99, per lane), retry and DLQ rates, payload size distribution, cache hit rate, timeouts.
- Domain optimizations:
- Cache the parsed template (a list of literal and placeholder segments) in an LRU keyed by a content hash, so repeats skip parsing.
- Render in a single pass with a builder, not repeated string replace.
- Batch small jobs per message to amortize overhead.
- Stream very large templates instead of loading them whole.
Common mistakes
- Treating CPU as the bottleneck and ignoring large-payload outliers.
- Acking before the result is stored, which loses jobs on crashes.
- Unbounded in-memory buffers, which remove backpressure.
- Hashing on a low-cardinality key and creating hot partitions.
- Forgetting a DLQ and a retry policy that distinguishes transient from permanent errors.