{"id":10602,"date":"2026-11-30T03:58:30","date_gmt":"2026-11-30T03:58:30","guid":{"rendered":"https:\/\/cybersecurityinfocus.com\/?p=10602"},"modified":"2026-11-30T03:58:30","modified_gmt":"2026-11-30T03:58:30","slug":"design-a-distributed-notification-system-queues-retries-and-reliable-delivery","status":"publish","type":"post","link":"https:\/\/cybersecurityinfocus.com\/?p=10602","title":{"rendered":"Design a Distributed Notification System: Queues, Retries and Reliable Delivery"},"content":{"rendered":"<p class=\"wp-block-paragraph\">Imagine a hypothetical commerce platform called ShopSquare. Priya places an order during a festival sale and expects a confirmation <a href=\"https:\/\/programesecure.com\/email-organization-system-inbox-zero-guide\/\">email<\/a>, while Rahul needs an urgent delivery update by SMS. At the same moment, a promotional campaign sends millions of push notifications. The SMS provider slows down, but checkout must remain responsive. How can one platform deliver all these messages reliably without overwhelming its dependencies?<\/p>\n<p class=\"wp-block-paragraph\"><strong>Difficulty:<\/strong> Intermediate to advanced \u00b7 <strong>Prerequisites:<\/strong> HTTP, SQL, queues \u00b7 <strong>Reading time:<\/strong> approximately 20 minutes<\/p>\n<p class=\"wp-block-paragraph\">The central design challenge is not sending a message. It is making a durable promise to attempt delivery while controlling duplicates, latency and failures.<\/p>\n<h2 class=\"wp-block-heading\">1. Define the problem before drawing boxes<\/h2>\n<p class=\"wp-block-paragraph\">Our service accepts notification requests from trusted business applications. It owns template selection, consent checks, asynchronous delivery and tracking. The order service owns order correctness; it should not wait for a third-party SMS response. We will design transactional messages and marketing messages with different priorities. We exclude building telecommunications infrastructure and guaranteeing that a human reads a message.<\/p>\n<p>Priya places an order: the order service requests email and push confirmation.Rahul changes delivery preferences: subsequent marketing requests must respect the change.A support agent queries a notification and sees which channels were accepted, delivered, failed or expired.<\/p>\n<h2 class=\"wp-block-heading\">2. Gather requirements<\/h2>\n<p>Functional requirementBehaviorAccept requestsReturn a durable notification ID and accept multiple channels.Templates and preferencesValidate template variables, locale and consent before delivery.Delivery trackingExpose channel-level states and process provider callbacks.Retries and recoveryRetry transient failures; quarantine exhausted or invalid jobs.Priority isolationReserve capacity for time-sensitive transactional traffic.Non-functional requirementIllustrative target and implicationAcceptance latencyp95 under 200 ms; exclude provider calls from the API path.Availability99.9% monthly acceptance objective; deploy across availability zones.DurabilityDo not acknowledge requests until the transaction commits.ConsistencyStrong uniqueness for request identifiers; eventually consistent delivery status.PrivacyTenant isolation, limited recipient-data retention and encrypted transport.<\/p>\n<p class=\"wp-block-paragraph\">Ask the interviewer whether notification requests can fan out to multiple recipients, whether per-recipient ordering is required, whether providers offer idempotency keys, what qualifies as delivery, and how long an OTP remains valid. A notification service cannot promise identical latency for every channel. Separate acceptance and delivery objectives to avoid hiding provider failures behind a healthy API metric.<\/p>\n<h2 class=\"wp-block-heading\">3. Capacity estimation: turn assumptions into decisions<\/h2>\n<p class=\"wp-block-paragraph\">Assume 10 million channel delivery jobs daily, not 10 million multi-channel requests. If an average request has two channels, that corresponds to roughly five million requests per day. Assume a peak multiplier of ten, a 1 KB persisted job record, seven days of hot retention and 100 ms average provider request duration. These are design assumptions, not measured ShopSquare traffic.<\/p>\n<p>MetricCalculationResultAverage jobs\/s10,000,000 \u00f7 86,400116Peak jobs\/s116 \u00d7 101,160Hot raw storage10M \u00d7 1 KB \u00d7 770 GBPeak payload bandwidth1,160 \u00d7 1 KB1.16 MB\/sIn-flight calls1,160 \u00d7 0.1 s116Concurrency with headroom116 \u00f7 0.523230-minute full outage1,160 \u00d7 1,8002.088M jobs<\/p>\n<p class=\"wp-block-paragraph\">Storage excludes indexes, replicas, event history, outbox copies and database overhead. The concurrency estimate uses Little\u2019s law and assumes steady throughput and mean latency; load tests must validate it under tail latency. With 2,088,000 queued messages and 1,500 jobs\/s recovery capacity against 1,160 incoming jobs\/s, the backlog drains at only 340 jobs\/s: approximately 102 minutes. This matters more than whether a worker can process one message quickly. Provision recovery headroom or define which expired messages can be discarded.<\/p>\n<h2 class=\"wp-block-heading\">4. Evolve the architecture in four steps<\/h2>\n<h3 class=\"wp-block-heading\">Version 1 \u2014 Synchronous sending<\/h3>\n<p>Order service -&gt; Notification API -&gt; Email\/SMS provider -&gt; Response<\/p>\n<p class=\"wp-block-paragraph\">This is a reasonable prototype for a small application. A provider timeout now consumes API sockets and extends checkout latency. If the call actually succeeded but the response was lost, a client retry may send another message. Adding more API instances does not remove the dependency.<\/p>\n<h3 class=\"wp-block-heading\">Version 2 \u2014 Asynchronous queue<\/h3>\n<p>Order service -&gt; API -&gt; Durable queue -&gt; Worker -&gt; Provider<\/p>\n<p class=\"wp-block-paragraph\">The API can accept work while workers deliver it independently. Workers can scale based on backlog age. However, if the API writes a database row and publishes a message as two independent operations, a crash between them can leave a request with no queued work. Publishing first creates the opposite risk: a worker can observe a job whose transaction never committed.<\/p>\n<h3 class=\"wp-block-heading\">Version 3 \u2014 Transactional outbox<\/h3>\n<p>API -&gt; [Notification + Delivery + Outbox rows in one transaction]<br \/>\n                      |<br \/>\n                    Relay -&gt; Queue -&gt; Worker<\/p>\n<p class=\"wp-block-paragraph\">Insert the state and its corresponding outbox event in one transaction. A relay publishes committed events and marks them sent after broker confirmation. A crash after confirmation but before marking the event may publish the same job again. This is acceptable only if downstream processing can recognize duplicates. The outbox removes the unsafe dual write, not every possible duplicate.<\/p>\n<h3 class=\"wp-block-heading\">Version 4 \u2014 Isolated production channels<\/h3>\n<p>                         -&gt; Email queue -&gt; Email workers -&gt; Provider A<br \/>\nAPI -&gt; DB\/outbox -&gt; Relay -&gt; SMS queue   -&gt; SMS workers   -&gt; Provider B<br \/>\n                         -&gt; Push queue  -&gt; Push workers  -&gt; Provider C<br \/>\nProvider callbacks -&gt; Signed callback API -&gt; Delivery event store<\/p>\n<p class=\"wp-block-paragraph\">Separate worker pools prevent a blocked SMS integration from consuming every email worker. Within each channel reserve capacity for critical traffic and apply tenant quotas. The provider adapters hide channel-specific response formats. Keep status records independent of broker retention so support teams can diagnose failures long after queue messages expire.<\/p>\n<h2 class=\"wp-block-heading\">5. High-level design: responsibilities and flow<\/h2>\n<p>ComponentResponsibilityScaling and failure behaviorAPI gatewayAuthenticate, apply quotas, route requestsStateless replicas; reject overload with 429.Notification APIValidate input and commit job stateScale horizontally; fail safely if storage unavailable.Relational databaseAuthoritative requests, deliveries and outboxMulti-zone primary, backups and tested failover.Outbox relayPublish durable pending eventsMultiple leased pollers; monitor unpublished event age.Channel brokerBuffer jobs and enable redeliveryPartition and isolate workloads; bound retention.Workers\/adaptersCheck consent, claim jobs, call providersScale by age and latency within provider quotas.Callback APIAuthenticate and record delivery eventsDeduplicate events; tolerate reordering.<\/p>\n<p class=\"wp-block-paragraph\">For Priya\u2019s order, the application submits a stable request key derived from the order event. The API validates authorization, template and channel choices, commits the request plus two delivery rows and two outbox events, and returns 202. The relay publishes both channel jobs. Each worker acquires its own delivery lease and renders the template. The email adapter records provider acceptance; later a signed delivery callback may mark the email delivered. The push worker can finish independently.<\/p>\n<p>Order service    API       Database      Relay     Queue     Worker<br \/>\n     | POST       |            |            |         |         |<br \/>\n     |&#8212;&#8212;&#8212;&#8211;&gt;| BEGIN      |            |         |         |<br \/>\n     |            |&#8212;&#8212;&#8212;&#8211;&gt;| COMMIT     |         |         |<br \/>\n     |&lt;&#8211; 202 &#8212;-|            |            |         |         |<br \/>\n     |            |            |&lt;&#8211; poll &#8212;|         |         |<br \/>\n     |            |            |            |&#8211; job -&gt;|         |<br \/>\n     |            |            |            |         |&#8211; job -&gt;|<br \/>\n     |            |            |&lt;&#8212;&#8212;- durable delivery state-|<br \/>\n     |            |            |            |         |&lt;- ack &#8211;|<\/p>\n<h2 class=\"wp-block-heading\">6. Low-level design: delivery lifecycle and concurrency<\/h2>\n<p class=\"wp-block-paragraph\">Treat each delivery as an independent state machine. A notification with successful email and failed SMS is partially successful; do not overwrite these details with a single boolean. Store immutable attempts separately when audit history is required.<\/p>\n<p>PENDING -&gt; SENDING -&gt; ACCEPTED -&gt; DELIVERED<br \/>\n              |           |<br \/>\n              v           v<br \/>\n          RETRY_WAIT    FAILED<br \/>\n              |<br \/>\n              +&#8212;&#8211;&gt; PENDING<br \/>\nSENDING -&gt; UNKNOWN -&gt; RECONCILE<br \/>\nPENDING \/ RETRY_WAIT -&gt; EXPIRED \/ SUPPRESSED<\/p>\n<p class=\"wp-block-paragraph\">The worker uses a conditional database update to claim only an eligible row and increments a fencing token. A lease expires if the worker dies. Updates from a stale worker must include its token so it cannot overwrite the newer owner\u2019s state. This protects database state, but cannot retract an external provider call already made by a stale worker. Use a stable provider idempotency key where available and reconcile ambiguous results before attempting another send.<\/p>\n<p class=\"wp-block-paragraph\">Expiration should be checked immediately before dispatch. A one-time password that arrives after its validity window is useless. Marketing consent should also be checked at dispatch rather than only at acceptance; the system still cannot recall a message already accepted externally. Capture that limitation in the product contract.<\/p>\n<h2 class=\"wp-block-heading\">7. API design<\/h2>\n<p>Method and pathPurposeTypical responsesPOST \/v1\/notificationsAccept request; Idempotency-Key header202, 400, 401, 409, 429, 503GET \/v1\/notifications\/{id}Read tenant-scoped channel state200, 401, 404POST \/v1\/provider-events\/{provider}Receive signed delivery callback204, 400, 401POST \/v1\/notifications<br \/>\nIdempotency-Key: order-8421-confirmation<br \/>\nAuthorization: Bearer &lt;token&gt;<\/p>\n<p>{<br \/>\n  &#8220;recipient_id&#8221;: &#8220;customer-73&#8221;,<br \/>\n  &#8220;template_id&#8221;: &#8220;order-confirmed-v2&#8221;,<br \/>\n  &#8220;channels&#8221;: [&#8220;email&#8221;, &#8220;push&#8221;],<br \/>\n  &#8220;variables&#8221;: {&#8220;order_id&#8221;: &#8220;8421&#8221;},<br \/>\n  &#8220;priority&#8221;: &#8220;transactional&#8221;<br \/>\n}HTTP\/1.1 202 Accepted<br \/>\n{<br \/>\n  &#8220;notification_id&#8221;: &#8220;ntf-1001&#8221;,<br \/>\n  &#8220;status&#8221;: &#8220;accepted&#8221;,<br \/>\n  &#8220;deliveries&#8221;: {&#8220;email&#8221;: &#8220;pending&#8221;, &#8220;push&#8221;: &#8220;pending&#8221;}<br \/>\n}<\/p>\n<p class=\"wp-block-paragraph\">Scope the idempotency key to the authenticated tenant. Persist a canonical payload hash and return the original notification ID when the same key and payload arrive again. Return 409 for a different payload with the same key. Validate template variables, enforce allowed priorities and resolve tenant identity from credentials rather than request JSON. A 202 means durable acceptance, not that a phone or inbox has received the message.<\/p>\n<h2 class=\"wp-block-heading\">8. Database design and transaction boundaries<\/h2>\n<p>TableKey fields and constraintsPurposenotificationsid PK; tenant_id; idempotency_key; payload_hash; UNIQUE tenant\/keyDeduplicate acceptance.deliveriesid PK; notification_id FK; channel; state; lease_until; fence; UNIQUE notification\/channelTrack independent jobs.outboxid PK; delivery_id FK; created_at; published_atPersist pending broker work.provider_eventsprovider + event_id unique; delivery_id; received_atDeduplicate callbacks.attemptsdelivery_id + attempt number; outcome; latencyDiagnostic history.CREATE TABLE notifications (<br \/>\n id UUID PRIMARY KEY,<br \/>\n tenant_id UUID NOT NULL,<br \/>\n idempotency_key TEXT NOT NULL,<br \/>\n payload_hash TEXT NOT NULL,<br \/>\n created_at TIMESTAMPTZ NOT NULL DEFAULT now(),<br \/>\n UNIQUE (tenant_id, idempotency_key)<br \/>\n);<br \/>\nCREATE TABLE deliveries (<br \/>\n id UUID PRIMARY KEY,<br \/>\n notification_id UUID REFERENCES notifications(id),<br \/>\n channel TEXT NOT NULL,<br \/>\n state TEXT NOT NULL DEFAULT &#8216;PENDING&#8217;,<br \/>\n fence BIGINT NOT NULL DEFAULT 0,<br \/>\n lease_until TIMESTAMPTZ,<br \/>\n next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),<br \/>\n UNIQUE (notification_id, channel)<br \/>\n);<br \/>\nCREATE INDEX delivery_due_idx<br \/>\n ON deliveries(next_attempt_at) WHERE state = &#8216;RETRY_WAIT&#8217;;<\/p>\n<p class=\"wp-block-paragraph\">This illustrative schema omits templates, payload references, expiry and provider routing fields for brevity. Commit request, deliveries and outbox rows together. Use a unique index rather than a read-before-insert check, which races under concurrent requests. Partition large attempt histories by time and purge according to retention rules; retain request keys at least as long as the supported retry window. Database sharding by tenant may be useful when measured writes exceed a single primary\u2019s capacity, but introduces routing and cross-shard operational complexity.<\/p>\n<h2 class=\"wp-block-heading\">9. Deep dive: retries, outbox and backpressure<\/h2>\n<p class=\"wp-block-paragraph\">Suppose the relay publishes delivery D1, receives a broker confirmation, then crashes before committing its published marker. Another relay will publish D1 again. A worker that sees a terminal or accepted state should acknowledge the duplicate without initiating another provider call. For a timeout during sending, distinguish an explicit provider rejection from an uncertain side effect. Without idempotency or a provider lookup endpoint, there is no general way to guarantee exactly-once external delivery.<\/p>\n<p class=\"wp-block-paragraph\">For transient errors, choose capped exponential backoff with full jitter, limited by the delivery expiry and retry budget. For example, retry delays sampled from zero to two, four, eight and sixteen seconds distribute retries across time rather than creating a synchronized burst. A provider 429 should additionally respect its Retry-After guidance. Invalid recipient addresses and permanently rejected templates should not be retried unchanged.<\/p>\n<p class=\"wp-block-paragraph\">Backpressure protects the system when demand exceeds capacity. Apply quotas per tenant, provider and channel, and use queue-age thresholds to shed optional traffic. Reserve throughput for urgent messages. A circuit breaker can temporarily stop calls to an unhealthy provider, but design an explicit half-open probe policy. Do not blindly fail over uncertain sends to another provider: both providers could deliver the message.<\/p>\n<h2 class=\"wp-block-heading\">10. Technology choices and tradeoffs<\/h2>\n<p>ChoiceGood fitTradeoffPostgreSQL + polling outboxModerate traffic and strong transactional constraintsPolling load and cleanup overheadCDC relayHigh change volume and existing streaming platformConnector operations and schema evolutionRabbitMQTask queues and routingBroker operations and queue sizingKafkaReplayable event streams and partition orderingDelayed retries require additional designManaged task queueLow infrastructure burdenService quotas and vendor dependencyRedis token bucketFast distributed rate controlsDurability and failover semantics require care<\/p>\n<p class=\"wp-block-paragraph\">Start with PostgreSQL and a durable task queue when the primary problem is work dispatch. Choose Kafka if replay and multiple independent event consumers are central requirements, not merely because it is associated with large systems. A small deployment may even use database-backed jobs until measured contention justifies a broker. The design must be able to explain operational cost, ownership and recovery, not just peak throughput.<\/p>\n<h2 class=\"wp-block-heading\">11. Practical worker implementation<\/h2>\n<p>import random<\/p>\n<p>def retry_delay(attempt, base=2, cap=300):<br \/>\n    return random.uniform(0, min(cap, base * 2 ** min(attempt, 20)))<\/p>\n<p>def process(job, store, provider, queue):<br \/>\n    # Illustrative interfaces; durable store operations use fencing.<br \/>\n    lease = store.claim(job.id)<br \/>\n    if not lease:<br \/>\n        queue.defer_or_ack_if_terminal(job)<br \/>\n        return<br \/>\n    if store.expired_or_suppressed(job.id):<br \/>\n        store.finish(job.id, lease, &#8216;SUPPRESSED_OR_EXPIRED&#8217;)<br \/>\n    else:<br \/>\n        try:<br \/>\n            result = provider.send(job, idempotency_key=job.id)<br \/>\n            store.accept(job.id, lease, result.message_id)<br \/>\n        except AmbiguousTimeout:<br \/>\n            store.mark_unknown_and_schedule_reconciliation(job.id, lease)<br \/>\n        except TransientError as exc:<br \/>\n            delay = max(retry_delay(job.attempt), exc.retry_after or 0)<br \/>\n            store.retry_or_expire(job.id, lease, delay)<br \/>\n        except PermanentError:<br \/>\n            store.finish(job.id, lease, &#8216;FAILED&#8217;)<br \/>\n    queue.ack(job)<\/p>\n<p class=\"wp-block-paragraph\">The snippet is Python-style illustrative code, not a standalone runnable service. Exception classes and adapters must be supplied. Each durable state change must validate the lease token; retry scheduling must atomically persist a future outbox event or use a recoverable due-job scanner. Acknowledge only after that state change succeeds. An ambiguous timeout moves to reconciliation, not immediate resend. Input D1 with a successful provider response should persist ACCEPTED and acknowledge; input D1 with an invalid destination should persist FAILED without repeated attempts.<\/p>\n<h2 class=\"wp-block-heading\">12. Failure scenarios and recovery<\/h2>\n<p>IncidentDetection and impactResponse and preventionProvider outageError rate and oldest queue age rise; delayed deliveryOpen circuit, retain jobs, expire stale traffic; quota-limited drain.Relay crash after publishRepeated job ID; possible duplicateIdempotent consumer and stable provider key; monitor duplicate rate.Worker crashes after sendLease expires; provider result uncertainReconcile by provider reference\/key; never blindly resend.Database unavailableAcceptance error rate risesReturn 503, fail over, retry with original request key.Callback arrives out of orderOlder event follows newer stateDeduplicate and apply provider-specific valid transitions.Tenant floods marketing queueOther tenants face growing latencyFair quotas and reserved transactional capacity.<\/p>\n<p class=\"wp-block-paragraph\">Runbooks need explicit ownership. When an SMS outage begins, on-call engineers first check provider latency and errors, then queue age and expiry distribution. Reduce dispatch rate rather than adding unbounded workers. After recovery, increase traffic gradually and verify recovery throughput exceeds new arrivals. Replay dead letters only after fixing the cause and checking consent, expiry and duplicate risk.<\/p>\n<h2 class=\"wp-block-heading\">13. Scalability, security and observability<\/h2>\n<p class=\"wp-block-paragraph\">Deploy stateless APIs and workers across availability zones. Keep the database and broker in resilient configurations with tested restoration. For regional failure, define an explicit recovery point objective and recovery time objective; asynchronous replication can lose recent commits on failover, so it cannot promise zero <a href=\"https:\/\/programesecure.com\/protect-ai-data-security\/\">data<\/a> loss. Prefer a single write region per tenant initially to simplify uniqueness and avoid concurrent duplicate sends.<\/p>\n<p class=\"wp-block-paragraph\">Use scoped service credentials, secret rotation and signed callback verification including replay protection where supported. Encrypt recipient details and avoid putting message text, phone numbers or tokens into logs. Enforce tenant authorization on status reads and protect templates from injection. Store only required personal data and implement retention and deletion policies.<\/p>\n<p>MetricWhy it mattersAcceptance p95 and error rateMeasures caller experience independently of providers.Oldest pending job age by priorityReveals delivery delay and starvation.Provider latency, 429s and errorsSignals capacity exhaustion or outages.Unknown outcomes and duplicate rateMeasures ambiguity and safety of retries.Outbox lag and dead-letter volumeDetects lost progress and recovery workload.<\/p>\n<p class=\"wp-block-paragraph\">Correlate request ID, delivery ID and provider reference in logs and traces, without logging confidential payloads. Alert on sustained SLO burn and critical queue age. A growing queue is not always an incident if low-priority work remains within its deadline; age and priority provide more actionable signals.<\/p>\n<h2 class=\"wp-block-heading\">14. Testing strategy<\/h2>\n<p>TestScenarioExpected outcomeUnitRetry delay and expiry boundariesDelay stays within bounds; expired job is not sent.IntegrationConcurrent requests with identical keyOne notification and expected delivery\/outbox rows.ContractProvider returns 429 or invalid responseAdapter maps error correctly and honors retry guidance.ResilienceKill worker after provider acceptanceReconcile or deduplicate; stale token cannot overwrite state.LoadPeak traffic plus provider slowdownAcceptance SLO remains within target; backlog bounded by policy.RecoveryRestore database and replay outboxNo silent loss within stated RPO; duplicates handled.SecurityCross-tenant status request and forged callbackAccess denied; no unauthorized state change.<\/p>\n<p class=\"wp-block-paragraph\">Use a deterministic fake provider to reproduce ambiguous timeouts and repeated callback events. Verify both database invariants and external send counts when the fake supports idempotency. Run a soak test to detect connection leaks and lease accumulation. Measure latency distributions and queue-age recovery rather than relying on average request duration.<\/p>\n<h2 class=\"wp-block-heading\">15. Documented engineering principles<\/h2>\n<p class=\"wp-block-paragraph\">AWS provides a documented <a href=\"https:\/\/docs.aws.amazon.com\/prescriptive-guidance\/latest\/cloud-design-patterns\/transactional-outbox.html\" target=\"_blank\" rel=\"noopener\">transactional outbox reference implementation<\/a> using relational storage and a queue. Its example demonstrates why database changes and pending events belong in one transaction. Amazon\u2019s engineering article on <a href=\"https:\/\/aws.amazon.com\/builders-library\/timeouts-retries-and-backoff-with-jitter\/\" target=\"_blank\" rel=\"noopener\">timeouts, retries and jitter<\/a> explains how retries can amplify load and why bounded backoff is important. These are documented patterns, not evidence that ShopSquare or any particular retailer uses the exact architecture in this tutorial.<\/p>\n<h2 class=\"wp-block-heading\">16. How to approach the 45-minute interview<\/h2>\n<p>MinutesWhat to discuss0\u20135Clarify channels, delivery semantics, consent, urgency and traffic.5\u201310Estimate peak jobs, retention, provider concurrency and recovery capacity.10\u201320Draw synchronous design, show failure, evolve to outbox and queues.20\u201330Design API, unique keys, state machine and worker ownership.30\u201340Discuss ambiguous outcomes, quotas, outage recovery and observability.40\u201345Summarize tradeoffs and identify next scaling bottleneck.<\/p>\n<p class=\"wp-block-paragraph\">A beginner might propose an API and a queue. An intermediate engineer explains asynchronous delivery and retries. A senior answer makes guarantees explicit, distinguishes acceptance from actual delivery, analyzes the dual write and ambiguous timeout, and quantifies backlog recovery. Avoid spending interview time naming technologies before establishing requirements. Useful follow-up questions include whether the system must support bulk campaigns and whether a region may continue accepting writes while another is unavailable.<\/p>\n<h2 class=\"wp-block-heading\">17. Interview questions and detailed answers<\/h2>\n<h3 class=\"wp-block-heading\">Why not send notifications synchronously?<\/h3>\n<p class=\"wp-block-paragraph\">Synchronous calls couple business latency to external providers. During a provider outage, checkout threads may block and retries may duplicate sends. A durable asynchronous boundary makes acceptance fast and enables independent scaling, but requires status tracking and eventual delivery semantics.<\/p>\n<h3 class=\"wp-block-heading\">Does an outbox guarantee exactly-once delivery?<\/h3>\n<p class=\"wp-block-paragraph\">No. It ensures the business state and pending event commit together. The relay can publish twice after a crash, and another failure can happen after an external send. Use unique logical delivery IDs, conditional state transitions and provider idempotency or reconciliation. State precisely which boundary has which guarantee.<\/p>\n<h3 class=\"wp-block-heading\">How would you prioritize OTP traffic?<\/h3>\n<p class=\"wp-block-paragraph\">Use a separate urgent queue or reserved dispatch capacity, short expiry and provider-specific quotas. A shared FIFO queue can trap urgent messages behind marketing traffic. Strict priority without fairness can starve ordinary messages, so establish explicit capacity reservations and age objectives.<\/p>\n<h3 class=\"wp-block-heading\">What if a provider times out after accepting the message?<\/h3>\n<p class=\"wp-block-paragraph\">A timeout does not establish that no side effect occurred. Mark the attempt unknown, query the provider if possible or retry using the same supported provider idempotency key. If neither is available, choose a documented product policy balancing missed and duplicate delivery.<\/p>\n<h3 class=\"wp-block-heading\">How do you calculate worker capacity?<\/h3>\n<p class=\"wp-block-paragraph\">Multiply peak dispatch rate by mean service time to estimate in-flight work. At 1,160 jobs\/s and 100 ms, the estimate is 116 concurrent calls; target 232 with 50% utilization. Validate with load tests, account for tail latency and cap throughput at provider quotas. More workers cannot defeat an external rate limit.<\/p>\n<h3 class=\"wp-block-heading\">How do you handle duplicate or reordered callbacks?<\/h3>\n<p class=\"wp-block-paragraph\">Store a unique provider\/event identifier and process events transactionally. Apply valid transitions according to provider semantics rather than blindly accepting the newest arrival timestamp. Keep event history to explain unusual transitions and reconcile against provider records.<\/p>\n<h3 class=\"wp-block-heading\">When would you shard the database?<\/h3>\n<p class=\"wp-block-paragraph\">Only after measuring a bottleneck that indexing, batching, retention and vertical scaling cannot solve. Tenant-based sharding preserves local idempotency constraints but complicates cross-tenant operations and rebalancing. Avoid global transactions by keeping all delivery rows for one request on the same shard.<\/p>\n<h3 class=\"wp-block-heading\">How do you recover from a large backlog?<\/h3>\n<p class=\"wp-block-paragraph\">Calculate arrivals versus sustainable dispatch capacity. If arrival rate remains greater than service rate, backlog cannot shrink. Reserve urgent capacity, expire obsolete work and ramp provider traffic within quotas. Track oldest job age and estimate drain time from the net service rate, not the total worker count.<\/p>\n<h2 class=\"wp-block-heading\">18. Hands-on exercise<\/h2>\n<p class=\"wp-block-paragraph\">Build a single-channel service with PostgreSQL, a fake provider and a durable queue. Inject a crash immediately after the provider accepts a job. Add a stable provider key and reconciliation logic; compare external send counts before and after. Then simulate 1,160 incoming jobs\/s against a 500 jobs\/s provider for ten minutes. The backlog grows by 396,000 jobs. Design an admission and expiry policy to protect urgent messages. Evaluate your solution using unique request count, delivery state correctness, queue age and measured drain time.<\/p>\n<h2 class=\"wp-block-heading\">19. Two-minute revision<\/h2>\n<p>Acknowledge requests only after durable commit.Use an outbox to bridge database and broker safely; expect duplicate events.Isolate channels and priorities; scale against queue age and provider budgets.Use stable idempotency keys and fenced state transitions; reconcile uncertain sends.Bound retries with jitter, expiry and quotas.Measure acceptance separately from provider delivery; test failures deliberately.<\/p>\n<h2 class=\"wp-block-heading\">20. Conclusion and next steps<\/h2>\n<p class=\"wp-block-paragraph\">A reliable notification system is built around explicit guarantees, not a collection of fashionable tools. Start with durable acceptance and one worker, prove recovery under crashes, then introduce channel isolation and quotas. Extend the prototype with callbacks and load tests before adding multi-region complexity. For related design problems, read our <a href=\"https:\/\/programesecure.com\/payment-webhook-receiver-system-design\/\">Payment Webhook Receiver<\/a> and <a href=\"https:\/\/programesecure.com\/design-distributed-job-scheduler\/\">Distributed Job Scheduler<\/a> tutorials.<\/p>","protected":false},"excerpt":{"rendered":"<p>Imagine a hypothetical commerce platform called ShopSquare. Priya places an order during a festival sale and expects a confirmation email, while Rahul needs an urgent delivery update by SMS. At the same moment, a promotional campaign sends millions of push notifications. The SMS provider slows down, but checkout must remain responsive. How can one platform [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":10603,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-10602","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10602"}],"collection":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10602"}],"version-history":[{"count":0,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10602\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/media\/10603"}],"wp:attachment":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10602"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10602"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10602"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}