Guide
Premium
Intermediate
Real Projects

PostgreSQL Read Replicas and Replication Lag: Read Routing, Read-Your-Writes and WAIT FOR

A practical guide to serving reads from replicas without handing anyone the past: how a change actually travels from primary to replica and what each of the four clocks in pg_stat_replication measures (sent, write, flush and replay), why the seconds-based lag metric almost everyone ships first lies on an idle primary and the query that fixes it, Prometheus alerts built on your own postgres_exporter queries instead of metric names that change between versions, the five real causes of lag —single-process replay, replicas with fewer IOPS than the primary, recovery conflicts and the max_standby_streaming_delay that cancels your queries after 30 seconds, huge transactions, and a forgotten recovery_min_apply_delay—, the five levels of synchronous_commit and what each one costs, quorum commit with ANY and FIRST plus the two traps that cause real incidents (remote_apply with ANY 1 does not make every replica current, and an unsatisfiable quorum stops COMMITs with no timeout), the hot_standby_feedback trade-off between query cancellations on the replica and bloat on the primary, and read routing in the application —never by SQL text— with two pools, background health probing and lag-based eviction. It covers all four read-your-writes strategies: primary pinning with a TTL, LSN tokens with the new WAIT FOR command in PostgreSQL 19 and its four modes, the client-side polling fallback for PostgreSQL 18 and earlier (including the exact reason pg_wal_replay_wait was reverted before release), and lag-aware routing per read class. Includes the format validation that prevents SQL injection in a command that takes no bind parameters, the token max() without which concurrent requests move it backwards, why comparing LSNs as strings gives wrong answers, slots that fill pg_wal with max_slot_wal_keep_size and PostgreSQL 18 idle_replication_slot_timeout, what breaks on promotion and PostgreSQL 17 failover slot synchronisation, a complete write/read endpoint pair, eight recurring mistakes, a twelve-point production checklist and an FAQ. With production-ready SQL, Python, TypeScript, YAML and configuration.

32 minutes read
Josue Garcia
2 views

Verificando acceso...

Loading comments...

Related Resources

Guía
PREMIUM

API Errors with Problem Details (RFC 9457): One Standard Format, Stable Types, and Clients That Stop Parsing Strings

A practical guide to standardising your API errors with Problem Details (RFC 9457): the anatomy of type, title, status, detail and instance, extension members, validation with multiple errors, centralised FastAPI implementation, a TypeScript client that branches on type, security (what not to reveal), OpenAPI documentation, contract tests, common mistakes and an adoption checklist. With code in Python, TypeScript, YAML and HTTP. Expanded edition of 12 October 2026: the type catalog as a contract (stable URIs, about:blank, the IANA registry and evolution rules), a problem registry in code that generates the docs, domain exceptions and a central FastAPI handler with headers and localization, a robust TypeScript client with retries, Retry-After and jitter, per-type metrics and alerts, migrating without breaking clients, Spring, ASP.NET and Node, async errors, batches and idempotency, a case study, FAQ and glossary. Expansion of October 16, 2026: the boundaries almost nobody covers: errors generated by gateways and proxies (nginx and Envoy local_reply_config), a client that survives intermediary HTML responses, errors in the middle of an SSE or NDJSON stream with a terminal frame and resume cursor, partial failures in batches, disciplined design of extension members with extra="forbid", linting with Spectral, fuzzing with Schemathesis, client tests with MSW and a runbook for spikes in one problem type.

Guía
PREMIUM

API Versioning and Contract Testing: Safe Changes, OpenAPI in CI, Pact, and Retiring Endpoints with Sunset

A practical guide to changing your APIs without breaking the people who consume them: why compatibility rules invert between the request and the response —and why widening a returned enum breaks clients even though you are "only adding"—, the tolerant reader pattern in Pydantic with an escape hatch and a metric, OpenAPI generated from the code and diffed on every pull request with oasdiff (including the git diff --exit-code step without which the whole check is theatre), consumer-driven contract testing with Pact: type matchers instead of literal values, well-designed provider states, version selection with deployed_or_released, and the gate that actually makes it safe, can-i-deploy paired with record-deployment. It also covers rolling this out without stopping the factory using pending and WIP pacts, bi-directional contracts when the provider is a third party, the three versioning strategies with their real operational costs, why versioning the whole API for a single endpoint guarantees nobody migrates, retiring versions with the Deprecation (RFC 9745) and Sunset (RFC 8594) headers plus the migration Link, the per-consumer metric without which no sunset date is ever met, brownouts returning 410 Gone before the final shutdown, and the BACKWARD, FORWARD and FULL compatibility modes for event schemas. With production-ready code in Python, YAML, Bash and PromQL, eight recurring mistakes, a production checklist, FAQ and glossary. It also extends the contract beyond the happy path: errors with RFC 9457 (problem+json), cursor pagination and defaults as part of the contract, the expand/contract pattern for renaming a field across database and API with no maintenance window, governance with Spectral, buf breaking for gRPC and Protobuf, GraphQL schema evolution with @deprecated and real per-field usage, and semantic versioning of generated SDKs. It also covers the contracts that never show up in the schema and break just as hard: outbound webhooks with the version pinned on the subscription, HMAC signing with a timestamp window and key rotation, Idempotency-Key for safe POST retries, the RateLimit and RateLimit-Policy headers —and why lowering a limit is a breaking change—, and OAuth scopes, the blind spot no OpenAPI diff will ever catch.

Guía
PREMIUM

Architecture Decision Records (ADRs): Document the Why Behind Your Technical Decisions

A practical guide to recording architecture decisions with ADRs: what they are and are not, when to write one, a template covering context, alternatives and consequences, a lifecycle with statuses and supersession, and automation with a creation script and a CI validator. With Bash, Python and YAML code, common mistakes and a checklist. Expanded edition of October 2, 2026: writing context with evidence, alternatives without straw men and a weighted decision matrix with sensitivity analysis, Nygard, MADR 4 and Y-statement templates, the advice process with roles, CODEOWNERS and a PR template, the boundary between ADRs, RFCs, design docs and runbooks, ADRs as executable architecture with import-linter and fitness tests, generated index and supersession graph, scheduled reviews with Review-by, two complete annotated ADRs, ADRs at scale in monorepos and multi-repo setups, adoption through retroactive ADRs, ADRs as context for coding assistants, health metrics, advanced mistakes, FAQ and glossary.