Spring Boot Cookbook
“How would you do X?” — practical, production-ready recipes with the approach, full code, pitfalls and variations.
Spring Boot
- 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.