How to Test Database Code with Test Containers
Test against a real database: spin up a throwaway container per suite, migrate it, isolate test data, and tear it down reliably.
Step-by-step guides and in-depth articles to level up your skills.
Page 9 of 9
Test against a real database: spin up a throwaway container per suite, migrate it, isolate test data, and tear it down reliably.
Test the paths that are hard to reach: force each failure, cover boundaries and empty inputs, and assert the error shape and the cleanup.
Size pools with Little’s law, enable keep-alive, cap per-host sockets, and instrument wait time so connection setup stops taxing every request.
Configure keep-alive timeouts and pool sizes so clients reuse connections, avoid stale sockets, and cut handshake latency without leaking idle connections.
Split assets across hostnames to bypass HTTP/1.1 connection limits, know when sharding now hurts, and what replaces it on HTTP/2 and HTTP/3.
Use LATERAL joins to fetch the top N rows per group efficiently, compare with window functions, and index the inner query for speed.
Implement RFC 8288 Link headers for cursor and page pagination, emit correct rel values, and keep clients from parsing bodies for next links.
Shrink and speed indexes with a WHERE clause: index only the rows a query needs, keep the index small, and verify the planner uses it.
Pick unary, server-streaming, client-streaming, or bidirectional RPC by data shape, wire them with deadlines and flow control, and test partial results.
Verify uploaded file types by their magic bytes, not the extension or client content-type, and reject content that does not match its claimed type.
Verify inbound webhook signatures with HMAC over the raw body, constant-time comparison, timestamp tolerance, and secret rotation, without breaking idempotency.
Make time-dependent tests deterministic: inject a clock, advance it explicitly, and assert debounce, timeout, and expiry without real waits.
Write scripts that run on Linux, macOS, and Windows: use a real script runner, avoid the shell differences, and test each platform.
Build hash-chained, append-only audit logs that detect edits and truncation, with signed checkpoints, redaction, verification, and tests.
Design idempotency keys that survive retries: tenant scoping, atomic claims, concurrent requests, retention, and tests against duplicate effects.
Use leases, ownership tokens, and fencing to make distributed locks safe, and learn when Redis, databases, or consensus services fit.
Test migrations on the real engine: fresh installs, upgrades, backfills, lock behavior, rollback, and CI matrices that catch production surprises.
Choose a rate-limiting algorithm, implement an atomic Redis token bucket, return correct headers, and test the boundary without blocking legitimate users.
Replace offset pagination with stable keyset pagination, opaque cursors, correct ordering, and indexes that keep large result sets fast.
Store flexible documents in JSONB, index the keys you query, use containment and path operators safely, and avoid the performance traps of schemaless data.
Build a production-ready command-line tool in Node.js using Commander.js with subcommands, typed options, validation, exit codes, tests, and npm packaging.
Use SWR in React for cached, type-safe data fetching with revalidation, pagination, optimistic updates, retries, and tests that do not depend on the network.
Handle file uploads in FastAPI with UploadFile streaming, size limits, content checks, safe storage names, multiple files, and tests using TestClient.
Build an accessible React upload component with drag-and-drop, progress, cancellation, validation, previews, and server-side safeguards.
Build a testable Go CLI with Cobra: subcommands, persistent and local flags, required options, context cancellation, shell completion, and error exit codes.
Build a production-ready Go HTTP server with method routing, timeouts, structured logging, body limits, graceful shutdown, and httptest coverage.
Implement JWT auth in FastAPI with PyJWT, Argon2 hashing, scoped dependencies, refresh-token rotation, and tests for expired and invalid tokens.
Protect Next.js routes with edge-compatible JWT verification using jose, HttpOnly cookies, safe redirects, request headers, CSRF checks, and defense in depth.
Validate Python form and API data with Pydantic v2: strict fields, custom validators, nested models, normalized errors, JSON Schema, and FastAPI integration.
Build a typed Rust HTTP API with Axum 0.8: extractors, shared state, JSON errors, timeouts, tracing, graceful shutdown, and handler tests with tower.
Build a typed React form hook with validation timing, accessible errors, focus management, server errors, async checks, and tests for real user flows.
Build a typed Vue 3 form composable with reactive values, computed validation, touched fields, async submit state, server errors, and Vitest coverage.
Design APIs that survive years: explicit versioning, consistent pagination, idempotency for safety, clear errors, and hypermedia links for discoverability.
Build a design system that scales: design tokens for a single source of truth, composable components, theming, accessibility, and living documentation.
Build web components that work for everyone: semantic HTML, ARIA roles and states, keyboard navigation, focus management, and screen-reader testing.
Build command-line tools developers love: robust argument parsing, generated help text, sensible defaults, shell completion, and graceful errors.
Build reliable real-time features with WebSockets: connection lifecycle, heartbeat-driven reconnection, backpressure, and horizontal scaling with a pub/sub f...
A deep guide to resilient data fetching: exponential backoff, circuit breakers, jitter, and retry budgets for production services.
Choose the right cache for each layer, invalidate with tags and versions, and serve fresh data with stale-while-revalidate without thundering herds.
Token structure, signing algorithms, refresh tokens, rotation, and revocation strategies for secure JWT auth in production web apps.
Resolve configuration from many sources with explicit precedence, validate it at startup, and keep secrets out of code and logs with 12-factor discipline.
Run multi-service apps without Kubernetes: Docker Compose for local and staging, health checks, resource limits, graceful shutdown, and a path to scale.
Run schema changes safely with expand-contract migrations, backward-compatible code, and staged deployments that never lock out the old version.
Build file upload systems that handle large files: chunked uploads, resumable transfers, size and type guards, and async virus scanning.
Classify errors, propagate them with context, log and trace them without leaking secrets, and design recovery paths that keep production running.
Build a layered form validation architecture with Zod schemas, progressive enhancement, and accessibility from the server boundary to the UI.
Build three-pillar observability with structured logs, Prometheus metrics and alerting, and OpenTelemetry traces that connect user requests across services.
Find and fix performance bottlenecks with profiling, then lock in the gains with caching, budgeting, and continuous monitoring from local to production.
A practical tour of the browser security model: same-origin policy, CSP, CORS, XSS, and CSRF defenses that compose into a real boundary.
Structure your tests across the test pyramid: fast unit tests, contract-driven integration tests, and few high-value end-to-end tests in CI.
Make data transformations trustworthy with branded types, total parsers, and Result types that keep errors in the type system instead of the call stack.
Deploy without downtime using rolling updates, blue-green switches, canary releases, and feature flags, all gated by health checks and instant rollback.