Developer Cookbook
“How would you do X?” — practical, production-ready recipes with the approach, full code, pitfalls and variations.
FastAPI
All FastAPI recipes →- Add liveness and readiness endpoints to FastAPITell Kubernetes or a load balancer when an instance is alive and ready to receive traffic.
- Add OpenTelemetry tracing to FastAPISee where time goes in a request across your API, database and outbound HTTP calls.
- Add request IDs and structured logs to FastAPICorrelate every log line from one request and return the ID to clients for support.
- Build a WebSocket chat endpoint in FastAPIBroadcast messages to all users in a room in real time, across multiple app instances.
- Cache FastAPI responses in RedisSpeed up an expensive read endpoint and invalidate the cache when data changes.
- Call external APIs with retries and timeouts from FastAPIIntegrate a flaky third-party API without blocking workers or hammering it during outages.
- Implement role-based access control in FastAPIRestrict endpoints by permission and make sure users only access their own resources.
- Isolate tenants in a multi-tenant FastAPI appServe many customer organizations from one database without any data leaking between them.
- Paginate with cursors in FastAPIReturn large result sets page by page, fast and stable even while new rows are inserted.
- Rate limit FastAPI endpoints with RedisLimit login attempts and API usage per user or IP across multiple workers and instances.
- Return RFC 9457 Problem Details from FastAPIMake every error response — validation, not found, conflicts, crashes — use one consistent JSON shape.
- Run background jobs from FastAPI with ARQGenerate reports and send emails asynchronously with retries, outside the request.
- Run scheduled tasks alongside FastAPIRun a cleanup every hour and a report every night without duplicating work across replicas.
- Stream responses with Server-Sent EventsStream progress updates or LLM tokens to the browser as they're produced.
- Support Idempotency-Key headers in FastAPILet clients retry POST requests (like creating payments) safely without duplicate side effects.
- Test FastAPI endpoints against a real databaseWrite fast, isolated API tests that hit PostgreSQL but leave no data behind.
- Upload files directly to S3 from a FastAPI appLet clients upload large files without streaming them through your API servers.
- Use refresh tokens in HttpOnly cookies with FastAPIKeep users signed in for weeks while access tokens stay short-lived and safe from XSS.
- Verify incoming webhooks in FastAPIAccept webhooks from a payment provider securely and process each event exactly once.
- Version a FastAPI API without breaking clientsIntroduce breaking changes (renamed fields, new semantics) while existing clients keep working.
Next.js
All Next.js recipes →- Add a Content Security Policy with nonces in Next.jsMitigate XSS by allowing only scripts that Next.js itself renders.
- Add dark mode to Next.js without a flashSupport system/light/dark themes in a server-rendered Next.js app without hydration warnings or flashes.
- Add SEO metadata, Open Graph and sitemapsGive every page correct titles, descriptions, social previews and a sitemap for search engines.
- Avoid data-fetching waterfalls in Server ComponentsA dashboard page is slow because it awaits user, stats and notifications one after another.
- Build a validated JSON API with Route HandlersExpose a REST endpoint from a Next.js app for a mobile client, with auth and input validation.
- Create encrypted session cookies in Next.jsImplement login sessions without a session store, using a signed/encrypted cookie readable only on the server.
- Handle errors and 404s in the App RouterShow friendly error pages per section, recover with a retry, and return real 404s for missing records.
- Handle forms with Server Actions and validationCreate a contact form that validates on the server, shows field errors, and works without client-side JavaScript.
- Keep secrets and server code out of the client bundleMake sure API keys and database code never ship to the browser in a Next.js app.
- Optimistic UI with Server ActionsMake liking a post or adding a comment feel instant while the Server Action runs.
- Optimize images with next/imageServe responsive, lazy-loaded images in modern formats without layout shift, including from a CMS.
- Paginate and filter with searchParams in Server ComponentsBuild a searchable, paginated product list rendered on the server and shareable via URL.
- Pre-render dynamic pages with generateStaticParams and ISRServe thousands of blog/product pages as static HTML that refreshes periodically.
- Protect routes in the Next.js App RouterRedirect signed-out users away from /dashboard and make sure server code never serves private data to them.
- Rate limit Route Handlers and Server ActionsProtect login, signup and AI endpoints from abuse in a serverless deployment.
- Receive Stripe webhooks in a Next.js Route HandlerProcess payment events securely in a Next.js app deployed to serverless.
- Revalidate cached data with tags after a mutationShow fresh product data right after an admin edits it, while keeping pages fast and cached.
- Stream slow sections with SuspenseRender the page shell instantly while slow data (recommendations, analytics) loads.
- Test a Next.js app with Vitest and PlaywrightSet up fast component tests and a few end-to-end tests for critical flows in a Next.js project.
- Upload files with a Server ActionLet users upload an avatar through a form that works even before JavaScript loads.
Node.js
All Node.js recipes →- Add health and readiness endpoints to a Node.js serviceLet Kubernetes restart stuck processes and route traffic only to instances that can serve it.
- Add JWT authentication to an Express APIProtect Express routes with bearer tokens and expose the authenticated user to handlers.
- Cache expensive lookups in Redis from Node.jsReduce database load for a hot endpoint while avoiding stampedes when entries expire.
- Call external APIs with timeouts and retries in Node.jsMake outbound HTTP calls that never hang and recover from transient failures.
- Centralize error handling in Express 5Return consistent error responses and never leak stack traces, including for async handler failures.
- Hash passwords and implement login safely in Node.jsStore user passwords securely and build a login endpoint resistant to brute force and enumeration.
- Implement cursor pagination with PostgreSQL in Node.jsPaginate an activity feed efficiently with node-postgres, without OFFSET.
- Offload CPU-heavy work with worker threadsKeep an Express API responsive while generating PDFs or hashing large files.
- Process background jobs with BullMQSend emails and generate thumbnails outside the request cycle with retries and concurrency control.
- Rate limit an Express API across instancesThrottle login attempts and API calls per client, shared across all Node processes.
- Run database transactions correctly with node-postgresTransfer money between accounts atomically and avoid leaking pooled connections.
- Scale real-time Socket.IO across instancesBroadcast chat messages to rooms when users are connected to different Node instances.
- Shut down a Node.js server gracefullyDeploy without dropping in-flight requests or leaving database connections and jobs half-done.
- Stream a large CSV export in Node.jsExport millions of database rows as CSV without loading them into memory.
- Structured logging with request IDs in Node.jsProduce fast JSON logs where every line from a request carries the same request ID.
- Test an Express API with node:test and supertestWrite fast API tests without a separate test framework, including auth and validation cases.
- Upload files to S3 with presigned URLs from Node.jsLet clients upload large files directly to S3 while the API controls keys, types and sizes.
- Validate environment configuration at startupFail fast with a clear message when an env variable is missing or malformed, and get typed config.
- Validate Express requests with ZodReject invalid bodies and query strings with clear 422 errors and get typed data in handlers.
- Verify webhook signatures in ExpressAccept signed webhooks safely: verify the raw body, prevent replays and drop duplicates.
- Add CSRF protection to PHP formsPrevent cross-site request forgery on session-authenticated forms without a framework.
- Add health check endpoints to a PHP appLet load balancers and Kubernetes know whether a PHP instance is alive and ready for traffic.
- Add structured logging with request IDs in PHPMake PHP logs searchable and correlate all log lines from one request.
- Build a secure password reset flow in PHPLet users reset forgotten passwords without enabling account takeover or email enumeration.
- Cache expensive queries with Redis in PHPSpeed up a slow product listing query with Redis while keeping data reasonably fresh.
- Call external APIs with timeouts and retries in PHPCall a flaky third-party API without hanging PHP-FPM workers or amplifying outages.
- Handle file uploads securely in PHPAccept user image uploads safely: validate type and size, avoid executable files, and store them outside the web root.
- Implement rate limiting in a PHP APILimit each client to N requests per minute across multiple PHP-FPM servers and return 429 with Retry-After.
- Make a PHP payment endpoint idempotentPrevent double charges when clients retry a POST /payments request after a timeout.
- Paginate large tables with cursors in PHPList orders efficiently in an API without slow OFFSET queries on large tables.
- Prevent XSS in PHP templatesRender user-generated content (names, comments, links) safely in HTML pages.
- Protect a PHP API with JWT bearer tokensValidate JWT access tokens on every API request and expose the authenticated user to controllers.
- Receive and verify webhooks in PHPProcess payment provider webhooks safely: verify signatures, avoid duplicates and respond quickly.
- Retry deadlocked transactions in PHPHandle deadlocks and serialization failures gracefully in high-concurrency write paths.
- Run scheduled jobs (cron) reliably in PHPRun nightly reports and cleanups without overlapping runs or silent failures.
- Send emails asynchronously with a queue in PHPSend welcome and receipt emails without slowing down requests or losing them when the mail provider is down.
- Set up a PHP dev environment with Docker ComposeGive every developer the same PHP, database and Redis versions with one command.
- Test database code in PHP with transactionsWrite fast, isolated PHPUnit tests for repository code against a real database.
- Validate JSON API input in PHPValidate and normalize a JSON request body, returning all errors in a consistent 422 response.
- Wire a PHP app with a DI containerStop creating dependencies with `new` all over the code and make classes testable.
React
All React recipes →- Add optimistic updates to a todo listMake toggling and deleting items feel instant while staying correct if the server request fails.
- Build an accessible modal dialogShow a confirmation dialog that traps focus, closes with Escape and restores focus afterwards.
- Build infinite scroll with TanStack QueryLoad more items automatically as the user scrolls a long feed, using cursor pagination.
- Call a cookie-authenticated API with CSRF protectionYour SPA uses session cookies; send the CSRF token required by the backend on every mutating request.
- Debounce a search input in ReactSearch an API as the user types without firing a request on every keystroke or showing stale results.
- Handle errors gracefully with error boundariesShow a friendly fallback with a retry button when part of the UI crashes or fails to load data.
- Implement dark mode that follows the systemSupport light/dark themes with a manual override, persisted, and without a flash of the wrong theme.
- Poll a long-running job's statusShow progress for a report generation job until it finishes, then stop polling.
- Protect routes in a React SPAShow some pages only to signed-in users (and some only to admins), redirecting others to login and back.
- Refresh expired access tokens automaticallyRetry API calls transparently when the access token expires, without firing multiple refresh requests at once.
- Render 10,000 rows smoothly with virtualizationDisplay a very long list or table without freezing the browser.
- Respond to media queries in ReactRender different components for mobile and desktop and react to changes like dark mode or reduced motion.
- Show live updates over WebSocketsUpdate a dashboard in real time when the server pushes events, with reconnects.
- Show toast notifications from anywhereDisplay success and error messages from any component or mutation without prop drilling.
- Split your bundle by routeReduce initial JavaScript so the first page loads faster.
- Sync filters and pagination with the URLMake a filtered product list shareable and keep filters when the user refreshes or goes back.
- Test a data-fetching component with MSWWrite reliable tests for a component that loads data, including loading and error states.
- Upload files with a progress bar in ReactUpload large files directly to storage with a progress indicator and cancel button.
- Validate forms with React Hook Form and ZodBuild a signup form with field-level errors, server error mapping and accessible messages.
- Warn users about unsaved changesPrevent users from losing a half-filled form when navigating away or closing the tab.
Spring Boot
All Spring Boot recipes →- Add correlation IDs to Spring Boot logsTrace every log line of a request (and its outbound calls) with one ID returned to clients.
- Add retries and a circuit breaker with Resilience4jKeep your service responsive when a downstream dependency becomes slow or fails.
- Authenticate machine clients with API keys in Spring SecurityAllow server-to-server clients to call your API with hashed, revocable API keys.
- Cache service results in Redis with @CacheableSpeed up slow product lookups with a shared Redis cache and per-cache TTLs.
- Consume Kafka messages with retries and a dead-letter topicProcess order events reliably: retry transient failures, park poison messages, and never process twice.
- Handle concurrent updates with optimistic lockingPrevent lost updates when two users edit the same record, and retry automatically for background updates.
- Implement soft delete with HibernateLet users 'delete' records that can be restored and excluded from normal queries.
- Make POST endpoints idempotent in Spring BootPrevent duplicate orders or charges when clients retry a request after a timeout.
- Map entities to DTOs with MapStructStop hand-writing repetitive mapping code between JPA entities and API records.
- Paginate and sort safely with Spring DataExpose a paginated list endpoint with client-chosen sorting, without leaking entities or allowing arbitrary sort fields.
- Publish events reliably with the transactional outboxSave an order and publish an OrderCreated message to Kafka/RabbitMQ without losing or duplicating events on failures.
- Rate limit a Spring Boot API with RedisLimit each API client to N requests per minute across all instances and return 429 with Retry-After.
- Run scheduled jobs once across replicas with ShedLockRun a nightly cleanup with @Scheduled without every instance executing it.
- Send emails after a transaction commits in SpringSend a confirmation email only if the order was actually saved, without slowing down the request.
- Shut down Spring Boot gracefully on KubernetesDeploy new versions without dropping in-flight requests or failing health checks.
- Stream progress updates with Server-Sent EventsShow live progress of a long-running import in the browser.
- Test external API integrations with WireMockTest your RestClient-based integration with a payment API, including errors and timeouts, without calling the real service.
- Track created/updated timestamps and users with JPA auditingAutomatically fill createdAt, updatedAt, createdBy and updatedBy on every entity.
- Upload files to S3 from Spring Boot with presigned URLsLet browsers upload large files directly to S3 while your API controls who can upload what.
- Verify webhook signatures in Spring BootAccept signed webhooks from a provider, reject forgeries and replays, and process each event once.