A timeout is a relative duration for one hop—say 500 ms—whereas a deadline is an absolute cutoff shared across the call chain. Without deadline propagation, each hop resets its clock and downstream services waste CPU on requests the user already abandoned; propagating a deadline (natively in gRPC) lets every hop use remaining budget and fail fast when expired. I size timeouts off downstream p99 latency plus headroom, tightening from edge to database. Remember a timeout only stops the caller waiting: cooperative cancellation must propagate downstream, and because timed-out writes have unknown outcomes, retries require idempotency.
Only retry transient failures—connection resets, timeouts on idempotent calls, 503, or 429 honoring Retry-After—never 400, 401, business conflicts, or non-idempotent writes without an idempotency key. Between attempts, use capped exponential backoff with random jitter so overloaded downstreams get breathing room and clients don't synchronize into retry spikes. Most importantly, cap attempts and retry at only one layer: three tiers each retrying three times turn one user request into 64 downstream calls, causing a retry storm. Pairing a retry budget (for example, 10% of traffic) with a circuit breaker prevents retries from sustaining a metastable outage.
Key terms:exponential backoff, full jitter, retry storm, retry budget
Likely follow-up: "When is a hedged request better than a normal retry, and what makes it dangerous if left unbounded?"
A circuit breaker stops calling a failing or severely slow dependency so callers fail fast instead of exhausting threads while giving the downstream space to recover. It runs as a three-state machine: in CLOSED, calls flow normally and a sliding window tracks failure and slow-call rates; crossing the threshold trips it to OPEN, immediately rejecting calls; after a cool-down wait, HALF_OPEN lets a small batch of probe requests through to decide whether to close again or re-open. In production, three tuning details make or break it: set minimumNumberOfCalls so low traffic doesn't false-trip, include slow calls because slowness kills thread pools faster than errors, and ignore 4xx business exceptions.
Key terms:CLOSED / OPEN / HALF_OPEN, slow-call threshold, minimumNumberOfCalls, fail fast
Likely follow-up: "Should circuit breaker state be shared across service instances via Redis, or kept local per instance?"
A cascading failure happens when one slow downstream saturates a caller's threads, making the caller time out and triggering retries that multiply load up the entire call chain. Each resilience pattern stops a specific link in that chain: timeouts bound wait time—they're the prerequisite for everything else; retries absorb brief glitches; circuit breakers cut off sustained downstream failures; bulkheads isolate resources per dependency; and fallbacks degrade non-critical features gracefully. On the inbound side, rate limiting and load shedding protect your own capacity. I layer outbound policies from outside in—retry wrapping circuit breaker wrapping timeout and bulkhead—so every attempt respects timeouts and stops immediately once the circuit opens.
Service degradation intentionally sacrifices non-critical features or quality under dependency failures or overload to keep core flows alive—like serving stale cache, returning empty recommendations, toggling feature flags, or queuing async work, while failing fast on writes or financial data rather than faking results. Fallbacks carry four sneaky risks: calling another unprotected remote dependency that fails too, rotting untested until a real incident because the path rarely runs, silently masking downstream outages unless you alert on fallback metrics, and shifting traffic spikes onto another tier like the database. Keep fallbacks simple, local, regularly chaos-tested, and well-monitored.
Named after watertight ship compartments, bulkhead isolation caps the threads or connection pools each dependency can consume so one slow downstream never starves unrelated endpoints. Semaphore isolation bounds concurrency on the caller's own thread via a counter—minimal overhead, preserves ThreadLocal, and fails fast when full, though a stuck call blocks that thread unless its own timeout fires. Thread-pool isolation gives each dependency a dedicated pool and bounded queue for stricter isolation and caller-side timeouts, at the cost of thread-switching overhead and losing ThreadLocal context like trace IDs or security unless propagated. Unlike rate limiting (rate), bulkheads bound concurrency.
All three control load, but along different dimensions. Rate limiting caps request arrival rate per time window—typically using a token bucket to enforce API quotas and absorb short bursts while rejecting excess with 429. Concurrency limiting caps in-flight work: if you allow 100 QPS and downstream latency jumps from 50 ms to 5 seconds, concurrency spikes from 5 to 500 without ever tripping the rate limiter, so concurrency limits (static or adaptive) actually protect thread pools. Backpressure propagates slowness upstream—via bounded queues, TCP flow control, or Kafka's pull model—so producers slow down rather than building unbounded queues. In production, I combine edge rate limits, in-service concurrency caps, and bounded queues.
Because networks time out and clients retry, non-idempotent writes like payments must guarantee that executing a request multiple times has the same effect as executing it once. The standard approach is a client-generated Idempotency-Key scoped per user and endpoint, reused across every retry. For pure local DB writes, I insert the idempotency row (enforced by a unique constraint, never check-then-insert) and commit the business write in one atomic local transaction. When external calls like payment gateways are involved, I use a two-step state machine: commit a PROCESSING row first so concurrent retries see it and get 409, then update to SUCCEEDED or FAILED with the saved response (plus timeout recovery on crashes), always validating the request payload hash (422 on mismatch) with a TTL longer than the client retry window.
Key terms:Idempotency-Key, unique constraint, request hash, state machine
Likely follow-up: "What happens if your service crashes mid-request while the idempotency record is stuck in PROCESSING, or after calling a third-party payment gateway?"
追问3 个
为什么不能“先查再插”?
两个并发请求都查到不存在,都继续执行。必须依赖唯一约束这类原子操作(或 INSERT ... ON CONFLICT)。
消费端去重,通用的办法是 Inbox 模式,也就是一张已处理消息表。消费的时候,在处理业务的同一个数据库事务里,把消息的 ID 插到这张表里,上面有唯一约束。插入成功就继续做业务;如果唯一约束冲突,说明这条消息之前处理过了,直接跳过。因为去重记录和业务数据在一个事务里,所以是原子的。简单的场景也可以直接用业务上的唯一键,或者带状态条件的更新。
Because brokers default to at-least-once delivery—from retries, rebalances, or crashes before ack—consumers must deduplicate for effectively-once processing. In the Inbox pattern, you insert a stable event ID into a uniquely constrained inbox table inside the same local transaction as the business write, skipping cleanly on conflict (business unique keys or conditional state updates also work). On the producer side, the Outbox pattern avoids database-plus-broker dual-write bugs by writing events to an outbox table in that same local transaction, then publishing via polling or CDC like Debezium. Since the relay can crash post-publish, Outbox remains at-least-once—pairing Outbox and Inbox gives end-to-end reliability.
High availability assumes every component will fail and relies on five pillars. First, eliminate single points of failure with multi-AZ redundancy, database failover, and spare capacity. Second, keep services stateless so any node scales or replaces cleanly. Third, automate failure detection and recovery via health checks and orchestration. Fourth, contain blast radius with bulkheads, timeouts, and degradation—critical because serial hard dependencies multiply availabilities, compounding outage risk (two 99.9% services drop to 99.8%). Fifth, deploy progressively via canaries and auto-rollback since changes cause most incidents, backed by regularly tested disaster-recovery drills for target RPO/RTO. Each extra nine—from 8.8 hours to 53 minutes yearly—multiplies cost, so design to business SLOs.