Showing posts with label Backend Development. Show all posts
Showing posts with label Backend Development. Show all posts

Redis Caching in Spring Boot: Complete Guide with Java 17

Redis Caching in Spring Boot: A Complete Tutorial with Java 17 Example

Learn Redis caching in Spring Boot with a complete, working Java 17 example. This guide walks through the Cache-Aside pattern, the three Spring cache annotations, a real product API using MySQL and Spring Data JPA, and the production practices that keep caching reliable under load.

Here is a scenario I have seen more than once. A product detail API takes 80ms per request. At 10,000 requests, most of them asking for the same popular products, the database connection pool starts throwing warnings. Adding a Redis cache dropped the response time to a few milliseconds for cache hits and cut database load by roughly 70%. Nothing exotic — just storing data that was already fetched in memory so the next request does not repeat the same query.

The tricky part is not adding Redis. The tricky part is knowing when to write the cache, when to invalidate it, and what to do when it fails. This tutorial walks through all three.

What you will build: a Product Management REST API that reads product data from MySQL, caches it in Redis, and keeps the cache in sync when products are updated or deleted.

What Is Redis?

Redis (Remote Dictionary Server) is an in-memory data store that supports several data structures and is commonly used for caching, messaging, and low-latency data access. Unlike a traditional relational database, Redis keeps frequently accessed data in memory, which makes reads extremely fast.

Redis supports several data structures:

Type What it stores
String Text, numbers, and serialized values
Hash Field-value pairs
List Ordered collections of values
Set Unique values
Sorted Set Values with associated scores
Stream Append-only event data

For a product API, a cache key might look like products::101. Once the key is written, Redis can return the cached value on the next request without touching MySQL.

Why Do We Need Redis Caching?

Suppose your application receives 10,000 product API requests. Many customers are asking for the same popular products. Without caching, every request may execute a database query. With caching, repeated requests are served from Redis when a valid cache entry exists.

Metric Without caching With caching
Total API requests 10,000 10,000
Cache hits 0 ~7,000
Cache misses 10,000 ~3,000
Database reads 10,000 ~3,000
Database load Higher Lower

Note: these are illustrative numbers assuming a warm cache and no expiration during the measured requests. Actual results depend on workload and hit rate.

Major Benefits of Redis

  • Low-latency access: frequently requested data is served from memory.
  • Reduced database load: repeated queries are avoided.
  • Improved scalability: the database stays free for operations that need it.
  • Shared cache: multiple Spring Boot instances can use the same Redis deployment.
  • Flexible expiration: cached data can expire automatically with TTL.

How Redis Caching Works: The Cache-Aside Pattern

The most common caching approach is called Cache-Aside. The application checks the cache first. If the data is missing, it reads from the database and stores the result in the cache.

Cache-Aside architecture with Spring Boot, Redis, and MySQL A client sends a request to Spring Boot. Spring checks Redis first. On a hit, cached data is returned. On a miss, Spring queries MySQL and writes the result to Redis. Client / API Spring Boot Service + Cache Manager Redis Cache Cache Hit / Cache Miss MySQL Database Source of Truth 1. Check Redis 2. On cache miss 3. Store result 4. Return cached data to client

Cache-Aside: check the cache, fall back to MySQL on a miss, then write the result back to Redis.

Step-by-Step Request Flow

  1. Client sends a request to the Spring Boot REST API.
  2. Spring checks Redis for the requested cache key.
  3. If the key exists, Spring returns the cached result without calling the service method.
  4. If the key does not exist, the service method runs and retrieves data from MySQL.
  5. Spring stores the returned result in Redis.
  6. The next request can reuse the cached result.

The advantage is that the application controls when data enters the cache. The database does not need to know about Redis at all. The disadvantage is that the first request for any key is always slower, because it must query the database.

Treat the cache as a derived layer. If Redis is wiped, the application should still work — just slower. If Redis is treated as the source of truth, a restart becomes a data-loss event.

The Three Spring Cache Annotations

Before building the project, it helps to understand the three annotations Spring provides for caching. Each one answers a different question about what to do with the cache.

@Cacheable

Use @Cacheable when you want to cache the result of a method. On the first call, Spring runs the method and stores the result. On later calls with the same key, Spring returns the cached value and skips the method entirely.

@Cacheable(value = "products", key = "#id")
public ProductResponse getProduct(Long id) {
    return productRepository.findById(id)
        .map(this::toResponse)
        .orElseThrow(() ->
            new RuntimeException("Product not found"));
}

@CachePut

Use @CachePut when you want the method to execute every time and update the cache with its returned value. This is the right choice after an update operation, so the cache does not serve stale data.

@CachePut(value = "products", key = "#id")
public ProductResponse updateProduct(
        Long id, ProductRequest request) {
    // Update product in database
    // Return updated product response
}

@CacheEvict

Use @CacheEvict when you want to remove cached data. This is the standard approach after a delete, so the application does not keep serving a product that no longer exists.

@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
    productRepository.deleteById(id);
}

Quick Comparison

Annotation Purpose Executes method?
@Cacheable Read and cache result Only on cache miss
@CachePut Update cached result Always
@CacheEvict Remove cached result Always

Common Pitfall: Self-Invocation

Spring implements caching through a proxy. If a method inside ProductService calls getProductById on this, the call bypasses the proxy and the cache annotation is ignored. This is the single most common reason caching appears not to work.

// This call will NOT use the cache
public ProductResponse loadAndLog(Long id) {
    return getProductById(id); // self-invocation bypasses the proxy
}

The fix is to extract the cached method into a separate bean, or accept that the internal call will not be cached. For most applications, extracting into a dedicated service is the cleaner choice.

Build the Complete Spring Boot + Redis Application

Now let's implement a working example. We will create a Product Management API with create, read, list, update, and delete operations. Redis handles the caching, and MySQL remains the source of truth.

Spring Boot request path with Redis cache A request flows from the controller to the service. The service checks Redis. On a hit it returns. On a miss it calls the repository, which queries MySQL, then writes to Redis. Spring Boot Cache Request Path Controller @RestController Service @Cacheable @CachePut Redis Cache Repository Data Access MySQL Database Source of Truth hit miss On a miss, the repository result is written back to Redis automatically.

Step 1: Technology Stack

Language Java 17
Framework Spring Boot 3.5.x
Build tool Gradle
Database MySQL 8
Cache Redis 7
ORM Spring Data JPA / Hibernate
API testing Postman or curl

Step 2: Create the Spring Boot Project

Use Spring Initializr with the following settings: Gradle (Groovy), Java 17, Spring Boot 3.5.x, packaging Jar. Add these dependencies: Spring Web, Spring Data JPA, Spring Data Redis, MySQL Driver, and Validation.

Step 3: Configure Gradle Dependencies

Open build.gradle and configure the following dependencies:

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.5.5'
    id 'io.spring.dependency-management' version '1.1.7'
}

group = 'com.deepsingh44'
version = '1.0.0'

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

repositories {
    mavenCentral()
}

dependencies {

    implementation 'org.springframework.boot:spring-boot-starter-web'

    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

    implementation 'org.springframework.boot:spring-boot-starter-data-redis'

    implementation 'org.springframework.boot:spring-boot-starter-validation'

    runtimeOnly 'com.mysql:mysql-connector-j'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

Important: Spring Boot's dependency management selects compatible Spring Data Redis and Redis client versions. Avoid manually overriding these versions unless you have a specific compatibility requirement.

Step 4: Start Redis with Docker

For local development, Docker is the easiest way to run Redis.

docker run -d \
  --name redis-cache \
  -p 6379:6379 \
  redis:7

On Windows PowerShell, use the single-line form:

docker run -d --name redis-cache -p 6379:6379 redis:7

Verify the container is running:

docker ps

Connect to the Redis CLI and confirm the connection:

docker exec -it redis-cache redis-cli
PING

Expected response:

PONG

Production note: this command is for local development only. Production Redis should use authentication, private networking, TLS where appropriate, persistent deployment configuration, backups where required, and monitored resource limits.

Step 5: Configure MySQL

Create the database:

CREATE DATABASE redis_demo;

Hibernate will generate the product table for this learning example.

Step 6: Configure application.yml

server:
  port: 8080

spring:

  application:
    name: redis-caching-demo

  datasource:
    url: jdbc:mysql://localhost:3306/redis_demo
    username: root
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true

  data:
    redis:
      host: localhost
      port: 6379
      connect-timeout: 2s

  cache:
    type: redis

logging:
  level:
    org.springframework.cache: TRACE

Replace your_password with your local MySQL password. For production, use environment variables or a secret manager instead of committing database credentials to source control.

Step 7: Package Structure

com.deepsingh44
|
|-- RedisCachingApplication.java
|
|-- config
|   |-- RedisConfig.java
|
|-- controller
|   |-- ProductController.java
|
|-- dto
|   |-- ProductRequest.java
|   |-- ProductResponse.java
|
|-- entity
|   |-- Product.java
|
|-- repository
|   |-- ProductRepository.java
|
|-- service
    |-- ProductService.java

Step 8: Create the Product Entity

package com.deepsingh44.entity;

import jakarta.persistence.*;
import java.math.BigDecimal;

@Entity
@Table(name = "products")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private BigDecimal price;

    private String category;

    public Product() {
    }

    public Product(String name,
                   BigDecimal price,
                   String category) {
        this.name = name;
        this.price = price;
        this.category = category;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
}

Here, JPA annotations map the Java object to the MySQL products table.

Step 9: Create Request and Response DTOs

Keeping API request and response objects separate from database entities is good practice.

package com.deepsingh44.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.math.BigDecimal;

public record ProductRequest(

    @NotBlank(message = "Product name is required")
    String name,

    @NotNull(message = "Price is required")
    @Positive(message = "Price must be greater than zero")
    BigDecimal price,

    @NotBlank(message = "Category is required")
    String category

) {}
package com.deepsingh44.dto;

import java.io.Serializable;
import java.math.BigDecimal;

public record ProductResponse(
    Long id,
    String name,
    BigDecimal price,
    String category
) implements Serializable {}

The response DTO implements Serializable because the default Redis cache value serializer used in this example is Java serialization. For a production application that needs JSON interoperability, explicitly configure and test a suitable JSON serializer. Do not enable unrestricted polymorphic deserialization for untrusted Redis values.

Step 10: Create the Product Repository

package com.deepsingh44.repository;

import com.deepsingh44.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository
        extends JpaRepository<Product, Long> {

}

Spring Data JPA provides the common CRUD operations automatically, so no SQL queries are needed for this basic example.

Step 11: Configure Redis Cache

package com.deepsingh44.config;

import java.time.Duration;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

@Configuration(proxyBeanMethods = false)
@EnableCaching
public class RedisConfig {

    @Bean
    public RedisCacheManager cacheManager(
            RedisConnectionFactory connectionFactory) {

        RedisCacheConfiguration defaultConfig =
                RedisCacheConfiguration
                    .defaultCacheConfig()
                    .entryTtl(Duration.ofMinutes(10))
                    .disableCachingNullValues()
                    .prefixCacheNameWith("deepsingh44::");

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(defaultConfig)
                .withCacheConfiguration(
                    "products",
                    defaultConfig.entryTtl(
                        Duration.ofMinutes(15)
                    )
                )
                .build();
    }
}

The important configuration options:

  • @EnableCaching: enables Spring's caching infrastructure.
  • RedisConnectionFactory: provides the Redis connection used by Spring Data Redis.
  • RedisCacheManager: manages application caches backed by Redis.
  • entryTtl(): defines how long a cache entry remains valid.
  • disableCachingNullValues(): prevents null results from being stored.
  • prefixCacheNameWith(): namespaces application cache keys.

We have configured a 10-minute default expiration and a 15-minute expiration for the products cache.

Why is TTL important? Without a suitable expiration policy, cached information can remain available longer than intended. TTL provides a time-based safety mechanism, although it does not replace proper cache invalidation.

Step 12: Implement the Product Service

This is the most important part of the application. All caching operations live inside the service layer.

package com.deepsingh44.service;

import com.deepsingh44.dto.ProductRequest;
import com.deepsingh44.dto.ProductResponse;
import com.deepsingh44.entity.Product;
import com.deepsingh44.repository.ProductRepository;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductService {

    private final ProductRepository productRepository;

    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    // Create product
    @Transactional
    public ProductResponse createProduct(ProductRequest request) {

        Product product = new Product(
            request.name(),
            request.price(),
            request.category()
        );

        Product saved = productRepository.save(product);

        return toResponse(saved);
    }

    // Read product with Redis caching
    @Cacheable(
        value = "products",
        key = "#id",
        unless = "#result == null"
    )
    @Transactional(readOnly = true)
    public ProductResponse getProductById(Long id) {

        System.out.println("Fetching product from MySQL: " + id);

        Product product = productRepository.findById(id)
            .orElseThrow(() ->
                new RuntimeException("Product not found: " + id)
            );

        return toResponse(product);
    }

    // Get all products
    @Transactional(readOnly = true)
    public List<ProductResponse> getAllProducts() {

        return productRepository.findAll()
            .stream()
            .map(this::toResponse)
            .toList();
    }

    // Update product and refresh cache
    @Transactional
    @CachePut(
        value = "products",
        key = "#id"
    )
    public ProductResponse updateProduct(
            Long id,
            ProductRequest request) {

        Product product = productRepository.findById(id)
            .orElseThrow(() ->
                new RuntimeException("Product not found: " + id)
            );

        product.setName(request.name());
        product.setPrice(request.price());
        product.setCategory(request.category());

        Product updated = productRepository.save(product);

        return toResponse(updated);
    }

    // Delete product and remove cache
    @Transactional
    @CacheEvict(
        value = "products",
        key = "#id"
    )
    public void deleteProduct(Long id) {

        if (!productRepository.existsById(id)) {
            throw new RuntimeException("Product not found: " + id);
        }

        productRepository.deleteById(id);
    }

    private ProductResponse toResponse(Product product) {

        return new ProductResponse(
            product.getId(),
            product.getName(),
            product.getPrice(),
            product.getCategory()
        );
    }
}

How @Cacheable Works Here

Suppose the client requests product ID 101. Spring generates a cache entry using the products cache and the supplied ID. If a valid entry exists, the service method is skipped. If not, Spring executes the method, fetches the product from MySQL, and stores the returned response in Redis. The unless condition prevents caching a null result.

How @CachePut Works Here

When the product is updated, the method executes and the returned ProductResponse replaces the corresponding cache value.

How @CacheEvict Works Here

When the product is deleted successfully, the corresponding cache entry is removed.

Important production consideration: Spring cache annotations are proxy-based. A method calling another cached method through this inside the same class will generally bypass the cache interceptor. Also, a cache operation and a database transaction are not automatically one atomic operation. For applications requiring strict consistency, consider transaction-aware cache management, after-commit eviction, or an outbox / event-driven invalidation strategy.

Step 13: Create the REST Controller

package com.deepsingh44.controller;

import com.deepsingh44.dto.ProductRequest;
import com.deepsingh44.dto.ProductResponse;
import com.deepsingh44.service.ProductService;

import jakarta.validation.Valid;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @PostMapping
    public ResponseEntity<ProductResponse> createProduct(
            @Valid @RequestBody ProductRequest request) {

        return ResponseEntity
            .status(HttpStatus.CREATED)
            .body(productService.createProduct(request));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ProductResponse> getProduct(
            @PathVariable Long id) {

        return ResponseEntity.ok(
            productService.getProductById(id)
        );
    }

    @GetMapping
    public ResponseEntity<List<ProductResponse>> getAllProducts() {

        return ResponseEntity.ok(
            productService.getAllProducts()
        );
    }

    @PutMapping("/{id}")
    public ResponseEntity<ProductResponse> updateProduct(
            @PathVariable Long id,
            @Valid @RequestBody ProductRequest request) {

        return ResponseEntity.ok(
            productService.updateProduct(id, request)
        );
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(
            @PathVariable Long id) {

        productService.deleteProduct(id);

        return ResponseEntity.noContent().build();
    }
}

Step 14: Create the Main Application Class

package com.deepsingh44;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RedisCachingApplication {

    public static void main(String[] args) {

        SpringApplication.run(
            RedisCachingApplication.class,
            args
        );
    }
}

The basic Spring Boot Redis caching application is now complete.

Testing the Application

Start the Redis container, make sure MySQL is running, and run the Spring Boot application.

API 1: Create a Product

Method: POST — http://localhost:8080/api/products

Request body:

{
  "name": "Dell Laptop",
  "price": 65000,
  "category": "Electronics"
}

Example response:

{
  "id": 1,
  "name": "Dell Laptop",
  "price": 65000,
  "category": "Electronics"
}

API 2: Get Product by ID

Method: GET — http://localhost:8080/api/products/1

First request: the Redis key does not exist, so Spring executes the service method and fetches the product from MySQL. You will see this in the console:

Fetching product from MySQL: 1

Second request: send the exact same request again. Spring finds the product in Redis, the service method is skipped, and the MySQL log message does not appear again. That is your first cache hit.

API 3: Update Product

Method: PUT — http://localhost:8080/api/products/1

{
  "name": "Dell Laptop Pro",
  "price": 72000,
  "category": "Electronics"
}

The update runs against MySQL and refreshes the corresponding Redis cache entry with the updated response.

API 4: Delete Product

Method: DELETE — http://localhost:8080/api/products/1

After a successful delete, the corresponding cache entry is removed. A subsequent GET request will not find the product in MySQL and will return an error.

Verifying Cache Data in Redis

The API works, but how do we confirm that Redis actually contains the cached data?

docker exec -it redis-cache redis-cli
KEYS *

You should see a key similar to:

deepsingh44::products::1

Because Redis stores the value using Java serialization in this configuration, the value may not look like readable JSON. Check the expiration time:

TTL deepsingh44::products::1

Redis returns the remaining lifetime in seconds. A value of -2 means the key does not exist, while -1 means the key exists without an expiration.

For controlled local inspection, you can also watch commands:

MONITOR

Be careful with MONITOR in production — it can expose command data and create significant overhead.

Cache Hits, Misses, and Hit Ratio

Two terms come up constantly when discussing caching.

Cache Hit

The requested data is already available in Redis, so the database is not queried.

Request: GET /api/products/1
Redis:   Key exists
Result:  Return cached response
Database: Not queried

Cache Miss

The requested key is not in Redis, so the service runs and the result is stored back in the cache.

Request: GET /api/products/2
Redis:   Key not found
Result:  Execute service method
Database: Fetch product
Redis:   Store product response

Cache hit ratio is a useful metric for understanding cache effectiveness:

Cache Hit Ratio = Cache Hits / Total Cache Requests * 100

For example, if 8,000 out of 10,000 lookups are hits:

Cache Hit Ratio = 8000 / 10000 * 100
                 = 80%

A high hit ratio is not automatically good. Evaluate it alongside data freshness, memory usage, latency, and business requirements.

Other Redis Caching Strategies

Cache-Aside is not the only strategy. Knowing the alternatives helps when designing high-traffic applications.

1. Cache-Aside

The application checks the cache first. On a miss, it reads from the database and populates the cache.

Best for: product details, user profiles, frequently accessed reference data.

2. Read-Through Cache

The application requests data through the cache layer, and the cache provider loads missing data from the underlying source.

Best for: systems with a cache-loading abstraction that centralizes data loading.

3. Write-Through Cache

When data is written, both the cache and the database are updated as part of the write workflow.

Best for: workloads where keeping cached data updated during writes is important.

4. Write-Behind Cache

Changes are written to the cache first and persisted to the database asynchronously.

Best for: carefully designed high-write workloads where delayed persistence is acceptable and durability is handled properly. This introduces complexity around failures, ordering, retries, and data loss, so it should not be used casually for financial transactions.

Redis Caching in Microservices

Redis becomes especially useful when multiple Spring Boot services need access to frequently requested data.

Microservices sharing a Redis cluster An API gateway routes requests to multiple Spring Boot services. Each service uses a shared Redis cluster for caching, with a database layer as the source of truth. API Gateway User Service Spring Boot Payment Service Spring Boot Other Services Spring Boot Redis Cluster Shared caching infrastructure Database Layer

Multiple services can share a Redis deployment, but they should not automatically share every cache key or cached object. Use clear key namespaces, ownership boundaries, expiration policies, and invalidation mechanisms.

One important design principle: do not cache payment authorization decisions, or transaction states as if they were ordinary product descriptions. Financial operations require authoritative data, concurrency control, and carefully designed consistency guarantees.

Production Best Practices

Adding @Cacheable is easy. Designing a reliable caching strategy is the real engineering challenge.

Production Redis cache checklist Eight production readiness areas for a Redis cache: TTL, selective caching, key design, stampede prevention, failure handling, monitoring, sensitivity, and consistency. Production Readiness Checklist 1. TTL Always set a TTL Add jitter Match business rules 2. Selectivity Cache only hot data Avoid huge objects 3. Key Design Namespace keys Include params 4. Stampede TTL jitter Single-flight load 5. Failure Handling Timeouts & retries Fallback to DB 6. Monitoring Hit / miss ratio Memory & latency 7. Sensitivity Avoid secrets Encrypt if required 8. Consistency Evict after write Accept eventual Verify each area before exposing the cache to production traffic.

1. Always Define a Suitable TTL

Choose an expiration duration based on how frequently the data changes and how stale it is allowed to become.

Data type Illustrative TTL
Static reference data 30 minutes or longer
Product information 5–15 minutes
Dashboard summaries 1–5 minutes
Temporary verification data Business-defined short TTL

These are starting examples, not universal values. Always consider the data's business requirements.

2. Avoid Unnecessary Caching

Not every database query deserves a cache. Frequently changing data, large objects, highly unique queries, and data with strict consistency requirements may not benefit from caching at all.

3. Use Meaningful Cache Keys

Prefer predictable and namespaced keys:

product::101
customer::202
configuration::payment-limits

Include relevant parameters in the key when the result depends on more than one input.

4. Prevent Cache Stampedes

Imagine a popular cache entry expires while thousands of requests arrive simultaneously. Many requests may observe a cache miss and execute the same expensive database query at the same time. This is known as a cache stampede.

Possible solutions include:

  • Use randomized TTLs to avoid synchronized expiration.
  • Use request coalescing or single-flight loading.
  • Use carefully designed distributed locks where appropriate.
  • Refresh important cache entries before expiration.

5. Handle Redis Failures

Redis should not become an unplanned single point of failure for every request. Think about what should happen when Redis becomes unavailable:

  • Should the application fall back to MySQL for safe read operations?
  • Should the request fail when cached data is mandatory?
  • How will you prevent excessive database traffic during Redis outages?

Use connection timeouts, bounded retries, monitoring, and carefully designed fallback behavior. A retry on every request can make an outage worse.

6. Monitor Cache Performance

Monitor metrics such as:

  • Cache hit and miss ratio
  • Redis memory consumption
  • Evictions and expired keys
  • Redis command latency
  • Connection pool usage
  • Cache-related application errors
  • Database query volume

7. Avoid Caching Sensitive Information Unnecessarily

Never assume that Redis is automatically secure simply because it is an internal service. Do not casually cache passwords, authentication secrets, PINs, payment credentials, or sensitive personal information. If a legitimate use case requires sensitive data in a cache, apply appropriate data minimization, access control, encryption, TTL, and security review.

8. Accept Eventual Consistency

A cache operation and a database transaction are not automatically one atomic operation. Choose eviction over writing the new value when a race between concurrent updates is possible, and accept that a cache will always be eventually consistent with the database.

Common Caching Mistakes

Mistake Better approach
No TTL configured Define expiration policies.
Cache never updated after database changes Implement cache update or eviction.
Caching everything Cache based on actual access patterns.
Using unclear keys Use namespaces and consistent naming.
Ignoring Redis outages Design timeout and fallback behavior.
Using KEYS * in production Use targeted lookups or SCAN for controlled inspection.
Ignoring serialization compatibility Use deliberate, versioned serialization contracts.
Assuming Redis and MySQL are one transaction Design consistency and invalidation explicitly.

Redis vs In-Memory Caching

Java developers often ask an important question: why use Redis when Java already provides ConcurrentHashMap? Both store data in memory, but they solve different problems.

Feature ConcurrentHashMap Redis
Storage Application memory Redis server memory
Shared across instances No Yes
Network communication No Yes
TTL support Requires custom logic Built-in expiration
Data structures Java collections Rich Redis data structures
Independent scaling No Yes
Operational overhead Low Requires Redis infrastructure

Use an in-memory cache when local, instance-specific caching is sufficient. Choose Redis when multiple application instances need a shared cache or when Redis-specific features are required.

Improving Redis Caching Performance

  1. Choose the right serialization format: measure serialization and deserialization overhead.
  2. Keep cache values reasonably small: avoid unnecessarily large objects.
  3. Use connection pooling: configure appropriate Redis client resources.
  4. Use pipelining carefully: reduce network round trips for suitable independent operations.
  5. Monitor memory: select an appropriate memory limit and eviction policy.
  6. Optimize key design: avoid excessively large keys and uncontrolled key cardinality.
  7. Measure actual latency: benchmark end-to-end API performance instead of assuming every Redis lookup is free.

Frequently Asked Interview Questions

1. What is Redis?

Redis is an in-memory data store supporting multiple data structures. It is commonly used for caching, messaging, and low-latency data access.

2. Why do we use Redis with Spring Boot?

Redis helps reduce repeated database queries by storing frequently accessed information and serving subsequent requests from the cache. Spring Boot's caching abstraction makes it easy to add without rewriting business logic.

3. What is the difference between @Cacheable and @CachePut?

@Cacheable checks the cache and skips method execution when a valid entry exists. @CachePut always executes the method and updates the cache with its result.

4. What is @CacheEvict?

It removes one or more entries from the cache. It is useful when data is deleted or when an application needs to invalidate cached information.

5. What is TTL in Redis?

TTL stands for Time To Live. It specifies how long a Redis key remains available before expiration.

6. What happens when Redis is unavailable?

Cache operations can fail depending on the connection and application configuration. A production system should define timeouts, monitoring, and safe fallback behavior based on business requirements.

7. What is cache invalidation?

Cache invalidation is the process of removing or updating cached information when its underlying data changes.

8. What is a cache stampede?

It happens when many concurrent requests try to load the same missing or expired cache entry, causing repeated expensive database operations. Randomized TTLs, single-flight loading, and distributed locks help prevent it.

9. Is Redis a replacement for MySQL?

No. They serve different purposes. MySQL is a relational database used for persistent transactional data, while Redis is commonly used for low-latency access and caching.

10. What is the Cache-Aside pattern?

The application first checks the cache. If the data is missing, it retrieves it from the underlying database and then populates the cache.

11. What happens if two application instances update the same cache entry?

Both instances may write competing values. A distributed consistency strategy, versioning, or event-based invalidation may be needed depending on the application requirements.

12. Can we use Redis for payment transactions?

Redis can support auxiliary workloads such as rate limiting, temporary state, and caching reference data. It should not casually replace the authoritative transactional database or ledger for financial operations.

Your Redis Caching Checklist

Before adding a cache to any service, ask:

  • Is this data actually read-heavy? If not, a cache may add complexity without value.
  • How stale is this data allowed to become? The answer determines the TTL.
  • Do I have a clear invalidation path? Every write should evict or refresh the cache.
  • What happens if Redis goes down? Define fallback behavior explicitly.
  • Are my keys namespaced and readable? Use a consistent key convention.
  • Am I caching anything sensitive? If yes, review access control and encryption.
  • Will I monitor hit ratio and latency? Without metrics, you cannot tell whether caching helps.

Start small. Add caching to one growing endpoint and measure the effect before expanding it to the rest of the application.

Best Practices for Java Developers

  • Enable caching with @EnableCaching on a configuration class.
  • Always set a TTL and add jitter to avoid synchronized expiration.
  • Use @CachePut after writes and @CacheEvict after deletes.
  • Keep cached methods in a separate bean to avoid self-invocation issues.
  • Configure JSON serialization for readability and cross-language compatibility.
  • Never use KEYS * in production; use SCAN for targeted inspection.
  • Treat the cache as a derived layer — the application must work when Redis is empty.
  • Write unit and integration tests for cache hit, miss, update, and eviction scenarios.

Conclusion

Redis caching is one of the most useful techniques for improving the performance of Java and Spring Boot applications. But adding a cache is not simply about slapping @Cacheable on a service method. Developers need to understand expiration, invalidation, serialization, concurrency, consistency, and failure handling.

I'll be honest: I don't add Redis to every service. A query that takes 3ms does not need a cache. Small apps with two or three endpoints do not need the operational overhead. But for endpoints that are hit thousands of times per second and compute the same result each time, a Redis cache is one of the highest-leverage changes you can make. The returns are immediate and measurable.

If you are a fresher, start by understanding cache hits, cache misses, and the Cache-Aside pattern. Build the product API from this tutorial and watch the database log messages disappear on the second request. That moment makes the pattern click.

If you are an experienced developer, focus on cache stampedes, transaction boundaries, observability, and consistency across microservices. The interesting problems are not in adding caching — they are in keeping it reliable at scale.

The most important lesson is this: treat the cache as a derived layer, not as storage. Design the application so it still works correctly when Redis is empty, slow, or unavailable. If you can do that, caching becomes a performance tool instead of a reliability risk.

Related topics: Chain of Responsibility Design Pattern in Java, Spring Boot Performance Tuning, Distributed Locking with Redis, Spring Data Redis Configuration Guide, Cache Invalidation Strategies, Java Design Patterns with Real-World Examples


Keep Learning Java and Spring Boot

Enjoyed this tutorial? Explore more practical Java, Spring Boot, Hibernate, microservices, and system design articles on the blog.

Have you implemented Redis caching in a real-world Spring Boot application? Share your experience in the comments.

System Design Complete Guide: Fundamentals, Architecture, Scalability & Interview Questions

System Design: Complete Guide from Beginner to Advanced with Real-World Examples

Have you ever wondered what happens when thousands of people try to book tickets for the same concert at exactly the same time? Or how an application continues working when one of its servers suddenly goes down?

These are not just coding problems. They are system design problems.

Writing a method that works correctly is one thing. Building an application that continues working when millions of users access it, data grows every second, and services communicate across multiple machines is a completely different challenge.

System design helps us understand how to build software that is scalable, reliable, secure, maintainable, and capable of handling real-world traffic.

In this guide, we will start with the fundamentals and gradually move towards the concepts expected from experienced backend developers and software architects. We will also design a practical online ticket booking system and discuss common system design interview questions with answers.

Prerequisite: Basic knowledge of web applications, databases and backend development is helpful. You do not need previous distributed systems experience.


1. What Is System Design?

System design is the process of defining the architecture, components, databases, communication mechanisms, and infrastructure required to build a software application.

It answers questions such as:

  • How will users access the application?
  • How will requests be distributed across servers?
  • Where will application data be stored?
  • How will the system handle increasing traffic?
  • What happens if a server or database becomes unavailable?
  • How will different services communicate?
  • How can we prevent duplicate transactions?
  • How will we monitor performance and detect failures?

In simple terms, system design is about deciding how different parts of an application should work together to solve a business problem.

System Design vs. Software Development

Consider a simple requirement: build an application where users can book movie tickets.

A developer might start by creating a controller, service, repository, and database table. That is an implementation-level approach.

A system designer first thinks about the bigger picture:

  • How many users might search for movies simultaneously?
  • How will seat availability be maintained?
  • Can two users book the same seat?
  • How will payment failures be handled?
  • How will the system handle a sudden booking rush?

Both perspectives are important. Good system design connects business requirements with technical implementation.

2. Types of System Design

System design is commonly divided into two major categories.

High-Level Design (HLD)

High-Level Design describes the overall architecture of an application. It focuses on major components and how they communicate.

Typical HLD topics include:

  • Monolithic and microservices architecture
  • API Gateway and load balancing
  • Database selection and data distribution
  • Caching and message queues
  • Service-to-service communication
  • Scalability, availability, and fault tolerance
  • Deployment and infrastructure

Low-Level Design (LLD)

Low-Level Design focuses on the internal structure of individual components. It explains how classes, interfaces, methods, and design patterns work together.

Typical LLD topics include:

  • Class diagrams and object relationships
  • SOLID principles
  • Design patterns
  • Interfaces and abstractions
  • Object lifecycle and responsibilities
  • Exception handling and extensibility

Example: HLD explains that a ticket booking platform uses a booking service, payment service, database, and message broker. LLD explains the classes, interfaces, and methods inside the booking service.

3. Understand the Basic Architecture of a Web Application

Before discussing distributed systems, understand how a typical web application handles a request.

When a user opens an application and searches for available tickets, the request generally passes through multiple components.

Client / Browser / Mobile Load Balancer / API Gateway Application Server 1 API / Business Logic Application Server 2 API / Business Logic Application Server 3 API / Business Logic Cache Redis Database MySQL / PostgreSQL Illustrative architecture — components depend on application requirements
Figure 1: A typical web application request flow from client to database.

A typical request flow looks like this:

  1. The client sends an HTTP request.
  2. The load balancer distributes the request to an available application server.
  3. The API Gateway may perform authentication, routing, and rate limiting.
  4. The application executes business logic.
  5. The application checks the cache or retrieves data from the database.
  6. The response is returned to the client.

In a more advanced architecture, a message broker may handle background tasks such as sending notifications, generating reports, or processing events.

4. Essential System Design Concepts

These are the building blocks you should understand before designing a large-scale application.

4.1 Scalability

Scalability is the ability of a system to handle increased workload without unacceptable performance degradation.

There are two common approaches.

Vertical Scaling (Scale Up)

Increase the resources of an existing machine, such as CPU, RAM, or storage.

For example, upgrading a server from 8 GB RAM to 32 GB RAM.

Advantages:

  • Simple to implement.
  • Does not require distributing application instances.
  • Can be useful for smaller workloads.

Limitations:

  • Hardware has an upper limit.
  • Expensive upgrades may be required.
  • A single server can remain a single point of failure.

Horizontal Scaling (Scale Out)

Increase the number of machines or application instances handling requests.

For example, instead of running one application server, run five instances behind a load balancer.

Advantages:

  • Can support increasing traffic.
  • Improves fault isolation when designed properly.
  • Allows instances to be added or removed as workload changes.

Limitations:

  • Requires distributed communication.
  • Data consistency becomes more challenging.
  • Monitoring and deployment become more complex.

Interview tip: Horizontal scaling is not automatically better. The right choice depends on workload, cost, application architecture, and operational complexity.

4.2 Load Balancing

A load balancer distributes incoming traffic across multiple servers.

Without a load balancer, one server may receive all requests while other available servers remain unused.

Common load balancing algorithms include:

  • Round Robin: Distributes requests sequentially across servers.
  • Weighted Round Robin: Sends more requests to servers with higher configured capacity.
  • Least Connections: Selects a server with fewer active connections.
  • IP Hash: Uses client IP information to select a server.
  • Least Response Time: Uses response-time information when supported by the implementation.

Popular technologies include NGINX, HAProxy, cloud load balancers, and Kubernetes Service networking.

4.3 Caching

Caching stores frequently accessed data in a faster storage layer so the application does not need to repeatedly retrieve it from the primary database.

Imagine a movie listing application. Thousands of users may request the same movie details. Reading the same information from the database every time creates unnecessary load.

We can store frequently accessed movie information in Redis.

public Movie getMovie(Long movieId) {

    String cacheKey = "movie:" + movieId;

    Movie cachedMovie = redisTemplate.opsForValue()
            .get(cacheKey);

    if (cachedMovie != null) {
        return cachedMovie;
    }

    Movie movie = movieRepository.findById(movieId)
            .orElseThrow(() -> new RuntimeException("Movie not found"));

    redisTemplate.opsForValue()
            .set(cacheKey, movie, Duration.ofMinutes(10));

    return movie;
}

This example illustrates the cache-aside pattern: check the cache first, load from the database on a miss, and then populate the cache.

Important caching strategies:

  • Cache Aside: Application manages cache reads and writes.
  • Read Through: Cache layer loads missing data from the underlying store.
  • Write Through: Writes update the cache and underlying store through the configured cache mechanism.
  • Write Behind: Writes are first accepted by the cache and persisted later. This requires careful durability and recovery design.

Important cache challenges:

  • Cache Invalidation: How do we remove or update stale data?
  • Cache Stampede: What happens when many requests simultaneously miss the same cache entry?
  • Hot Keys: What happens when one key receives unusually high traffic?
  • Eviction: Which entries should be removed when memory is full?

Redis is a popular choice for distributed caching. However, cache consistency, expiration, memory limits, and failure behavior should be designed explicitly.

4.4 Database Selection

Choosing a database is an architectural decision. The best database depends on the data model, query patterns, consistency requirements, transaction needs, and operational constraints.

Relational databases (SQL)

Examples: MySQL, PostgreSQL, Oracle, and SQL Server.

  • Structured tables and relationships.
  • SQL querying.
  • Transactions and constraints.
  • Useful for relational business data.

NoSQL databases

Examples: MongoDB, Cassandra, and DynamoDB.

  • Different data models, depending on the database.
  • Flexible document or key-value structures in some systems.
  • Can support distributed data storage and high-volume workloads.
  • Query and consistency capabilities vary significantly by product.

Important: NoSQL does not automatically mean faster, and SQL does not automatically mean less scalable. Select a database based on actual access patterns and business requirements.

4.5 Replication

Replication means maintaining copies of data across multiple database nodes.

A common arrangement is:

  • Primary: Handles writes.
  • Replica: Receives replicated changes and may serve read traffic.

Replication can improve read capacity and availability, but asynchronous replication may introduce replication lag. A recently written record may not immediately appear on a replica.

4.6 Sharding

Sharding divides a large dataset into smaller partitions distributed across multiple database nodes.

For example, a booking platform could partition bookings by customer ID or another carefully selected key.

Common approaches include:

  • Range-Based Sharding: Records are distributed according to ranges of a key.
  • Hash-Based Sharding: A hash function determines the target shard.
  • Directory-Based Sharding: A lookup mechanism maps records to shards.

Sharding can increase storage and throughput capacity, but introduces cross-shard query, rebalancing, hotspot, and transaction complexity.

4.7 Message Queues

Not every operation needs to be completed during the user's HTTP request.

Consider booking a ticket. After a successful booking, the system may need to:

  • Send an email confirmation.
  • Send an SMS notification.
  • Generate an invoice.
  • Update analytics.

These tasks can be processed asynchronously using a message broker such as Apache Kafka or RabbitMQ.

Booking Service Publishes event Message Broker Kafka / RabbitMQ Durable event delivery* Notification Email / SMS Invoice Service PDF generation Analytics Service Event processing *Delivery guarantees depend on broker configuration and consumer design
Figure 2: Asynchronous processing with a message broker decouples services.

Advantages of asynchronous processing:

  • Reduces the amount of work performed in the synchronous request.
  • Allows independent services to process events.
  • Helps absorb traffic spikes when properly configured.
  • Supports retries and failure recovery.

But asynchronous systems also require careful handling of duplicate messages, ordering, retries, dead-letter queues, and eventual consistency.

4.8 API Gateway

An API Gateway acts as an entry point for requests going to multiple backend services.

It can handle:

  • Request routing.
  • Authentication and authorization integration.
  • Rate limiting.
  • Request and response transformation.
  • Logging and monitoring.

In a Spring Boot microservices environment, Spring Cloud Gateway is one option for implementing an API Gateway.

4.9 CDN (Content Delivery Network)

A CDN delivers static content such as images, videos, CSS, and JavaScript from geographically distributed edge locations.

Instead of every user downloading an image from the main application server, the CDN can serve a cached copy from a nearby location.

This reduces latency and decreases load on the origin infrastructure.

4.10 Rate Limiting

Rate limiting controls how many requests a client can make within a specified time window.

For example, an API might allow a user to make 100 requests per minute.

Common algorithms include:

  • Fixed Window Counter
  • Sliding Window Log
  • Sliding Window Counter
  • Token Bucket
  • Leaky Bucket

Rate limiting helps protect APIs from accidental overload, abusive clients, and certain traffic spikes. It should be designed alongside authentication and fair usage policies.

5. Important Distributed Systems Concepts

When an application runs on multiple servers and services, some problems become more complicated. This is where distributed systems concepts become important.

5.1 CAP Theorem

The CAP theorem describes a trade-off in distributed data systems when a network partition occurs.

  • Consistency: Every read receives the latest successful write or an error, according to the system's consistency model.
  • Availability: Every request to a non-failing node receives a response, though it may not contain the latest data.
  • Partition Tolerance: The system continues operating despite communication failures between parts of the distributed system.

When a network partition occurs, a distributed system must make a choice between preserving strong consistency and continuing to serve requests in the affected scenario.

CAP should not be simplified into the statement that a system permanently chooses only two properties in every situation. The trade-off becomes relevant when a partition occurs.

5.2 Strong Consistency vs. Eventual Consistency

Strong consistency: A successful write is immediately reflected in subsequent reads according to the system's guarantees.

Eventual consistency: Replicas may temporarily show different values, but are expected to converge if no new updates occur and replication succeeds.

Example:

After a user changes their profile picture, it may take a short time for every cached or replicated copy to display the new image. That can be acceptable.

However, ticket allocation requires much stricter coordination because two customers should not receive the same seat.

5.3 ACID Properties

ACID describes important transaction properties in relational database systems.

  • Atomicity: A transaction completes fully or does not take effect.
  • Consistency: A transaction preserves defined database rules and constraints.
  • Isolation: Concurrent transactions are controlled according to the selected isolation level.
  • Durability: Committed changes survive failures within the database's durability guarantees.

5.4 Idempotency

Idempotency means that repeating the same operation produces the same intended result rather than performing the business action multiple times.

Imagine a user clicks the Book button, but the network times out. The user clicks again because they do not know whether the first request succeeded.

Without idempotency, the system might create two bookings.

A common solution is an idempotency key:

POST /api/bookings
Idempotency-Key: 8d5f7a21-unique-request-id

{
  "eventId": 501,
  "seatId": "A-12"
}

The backend stores the key with the operation result. When the same key is received again, it returns the previously recorded result instead of repeating the operation.

For production systems, the key must be scoped appropriately, stored durably, and protected by a unique constraint or equivalent concurrency-safe mechanism.

5.5 Circuit Breaker Pattern

Suppose the booking service calls an external payment provider. The provider becomes unavailable and starts responding slowly.

Without protection, application threads may remain blocked while waiting for responses. Eventually, the booking service itself may become unavailable.

A circuit breaker helps prevent repeated calls to a failing dependency.

  • Closed: Requests are allowed through.
  • Open: Calls are rejected or handled through fallback logic.
  • Half-Open: A limited number of test calls are allowed to check recovery.

In Java applications, Resilience4j provides circuit breaker, retry, rate limiter, and bulkhead capabilities.

5.6 Retry and Timeout

A timeout prevents a service from waiting indefinitely for another service.

A retry attempts a failed operation again, usually under controlled conditions.

Good retry design includes:

  • Finite retry attempts.
  • Exponential backoff.
  • Random jitter to reduce synchronized retry spikes.
  • Retry only for failures that may be temporary.
  • Idempotency for operations that may be repeated.

Never blindly retry a payment or booking operation without considering whether the previous attempt may already have succeeded.

5.7 Saga Pattern

In microservices, one business operation may involve multiple independent services. A single traditional database transaction usually cannot cover all of them.

The Saga pattern coordinates a sequence of local transactions. If a later step fails, compensating actions can be executed to reverse or neutralize earlier business effects.

Example ticket booking flow:

  1. Reserve the selected seat temporarily.
  2. Initiate payment.
  3. Confirm the booking after successful payment.
  4. Release the seat if payment fails or the booking expires.

Compensation is a business action, not necessarily a literal rollback of database history. For example, a payment refund is a new transaction rather than erasing the original payment record.

5.8 Database Indexing

An index helps the database locate records without scanning every row.

For example, if users frequently search bookings using a booking reference, an index on that column may improve query performance.

CREATE INDEX idx_booking_reference
ON bookings (booking_reference);

Indexes also have costs:

  • They consume storage.
  • They increase the work required for inserts and updates.
  • Poor index selection can waste resources.
  • Composite index column order matters for query patterns.

Use query plans and production-like workloads to validate index choices.

6. Practical System Design: Online Ticket Booking Platform

Now let's combine these concepts into a practical architecture.

Imagine we are building a platform where users can search events, view available seats, reserve tickets, make payments, and receive booking confirmations.

6.1 Functional Requirements

  • Users can register and log in.
  • Users can search for events.
  • Users can view event details and seat availability.
  • Users can select and temporarily reserve seats.
  • Users can pay for a reservation.
  • Users can view booking history.
  • Users receive confirmation or failure notifications.
  • Administrators can create and manage events.

6.2 Non-Functional Requirements

  • Availability: The platform should remain accessible during normal infrastructure failures.
  • Performance: Search and booking operations should have defined latency targets.
  • Consistency: The same seat must not be confirmed for multiple customers.
  • Scalability: The platform should support traffic spikes during popular events.
  • Security: User information and payment-related operations must be protected.
  • Reliability: Failed operations should be recoverable and auditable.

6.3 High-Level Architecture

Web / Mobile Client API Gateway / Load Balancer User / Event Service Profiles and event search Booking Service Seat reservation and booking Payment Service Payment provider integration Cache Redis Booking Database Seats and reservations Payment Database Payment records Message Broker Kafka / RabbitMQ Notification Service Email / SMS External Payment Provider Secure payment API and webhooks Conceptual architecture. Actual service boundaries depend on scale and business requirements.
Figure 3: High-level architecture of an online ticket booking platform.

6.4 Database Design

A simplified relational model could contain the following tables.

users

  • id (Primary Key)
  • name
  • email
  • created_at

events

  • id (Primary Key)
  • event_name
  • venue_id
  • event_date
  • status

seats

  • id (Primary Key)
  • event_id
  • seat_number
  • status

bookings

  • id (Primary Key)
  • user_id
  • event_id
  • booking_reference
  • status
  • created_at

booking_items

  • id (Primary Key)
  • booking_id
  • seat_id
  • price

payments

  • id (Primary Key)
  • booking_id
  • provider_reference
  • amount
  • status
  • created_at

For a real implementation, add foreign keys, appropriate indexes, audit fields, unique constraints, and carefully selected transaction boundaries.

6.5 Preventing Double Booking

This is one of the most important design challenges in a ticket booking system.

Suppose seat A-12 is available. Two users select the same seat at almost the same time.

A simple application-level check is not enough:

if (seat.getStatus().equals("AVAILABLE")) {
    seat.setStatus("BOOKED");
}

Why? Both requests may read AVAILABLE before either request commits its update. This is a race condition.

One approach is a conditional database update:

UPDATE seats
SET status = 'HELD',
    hold_expires_at = ?
WHERE id = ?
  AND status = 'AVAILABLE';

Then check the number of updated rows:

  • One row updated: the seat was successfully held.
  • Zero rows updated: another request already changed the seat state.

This works because the database performs the conditional update atomically. A unique constraint on the relevant booking allocation can provide an additional safeguard.

For a production booking flow, we also need to consider:

  • Temporary reservation expiration.
  • Concurrent requests for multiple seats.
  • Transaction isolation and locking.
  • Payment timeouts and delayed callbacks.
  • Duplicate payment notifications.
  • Seat release after payment failure.

6.6 Booking API Design

Some example REST endpoints:

GET    /api/events
GET    /api/events/{eventId}
GET    /api/events/{eventId}/seats

POST   /api/bookings/hold
GET    /api/bookings/{bookingId}
POST   /api/bookings/{bookingId}/confirm
POST   /api/payments/initiate
GET    /api/payments/{paymentId}
POST   /api/payments/webhook

The payment webhook should be authenticated or cryptographically verified according to the provider's documented mechanism. Do not trust an arbitrary client request as proof of successful payment.

6.7 Handling Payment and Booking Failures

Consider this sequence:

  1. User selects a seat.
  2. Booking service places a temporary hold.
  3. User starts payment.
  4. Payment provider processes the request.
  5. Provider sends a verified callback.
  6. Booking service confirms the reservation.

Now imagine the payment succeeds, but the application does not receive the response because of a network failure.

The application must not immediately assume that payment failed.

A robust approach includes:

  • Use a unique payment reference and idempotency key.
  • Persist the payment attempt before or as part of the appropriate workflow.
  • Verify payment status using trusted provider responses.
  • Handle duplicate webhooks safely.
  • Use reconciliation to identify unresolved payment and booking states.
  • Define what happens when the temporary seat hold expires while payment is still pending.

This is where state machines, Saga orchestration, and reliable event processing become useful.

7. Monolithic Architecture vs. Microservices

One of the most common architecture discussions in system design interviews is choosing between a monolith and microservices.

Monolithic Architecture

A monolithic application keeps multiple business capabilities inside one deployable application.

For example, a ticket booking application may have user, event, booking, payment, and notification modules within a single Spring Boot project.

Advantages:

  • Simpler deployment.
  • Easier local development in many cases.
  • Direct method calls between modules.
  • Can use a single database transaction where appropriate.

Disadvantages:

  • Application deployment may affect the entire system.
  • Independent scaling of business modules is difficult.
  • Codebase complexity can increase over time.
  • Teams may become tightly coupled.

Microservices Architecture

Microservices divide an application into independently deployable services organized around business capabilities.

For example:

  • User Service
  • Event Service
  • Booking Service
  • Payment Service
  • Notification Service

Advantages:

  • Independent deployment.
  • Independent scaling.
  • Clearer ownership boundaries for teams.
  • Different services can use suitable technologies when justified.

Disadvantages:

  • Network failures and latency.
  • Distributed tracing and debugging complexity.
  • Data consistency challenges.
  • More deployment and infrastructure management.
  • More complicated end-to-end testing.

Practical advice: Do not choose microservices just because they sound modern. A well-structured modular monolith can be an excellent starting point. Split services when independent scaling, deployment, ownership, or business boundaries justify the additional complexity.

8. How to Estimate System Capacity

System design interviews often expect candidates to estimate workload before selecting infrastructure.

Let's take an example application with 1 million daily active users.

Assume each active user makes 20 requests per day.

Total daily requests:

1,000,000 × 20 = 20,000,000 requests per day.

Average requests per second:

20,000,000 ÷ 86,400 ≈ 231 requests per second.

If peak traffic is five times the average:

231 × 5 ≈ 1,155 requests per second.

This is only an initial estimate. Real traffic may be uneven, and different endpoints may have very different costs.

Next, estimate storage. Suppose each booking record consumes approximately 1 KB of logical data and the platform creates 500,000 bookings per day.

Daily logical booking data:

500,000 × 1 KB ≈ 500 MB per day.

For one year:

500 MB × 365 ≈ 182.5 GB.

This excludes indexes, database overhead, replicas, backups, audit records, and other related data. Production capacity planning must account for those additional requirements.

Useful questions during estimation:

  • How many users are active daily?
  • What is the read-to-write ratio?
  • What is the peak-to-average traffic ratio?
  • How much data is generated per request?
  • How long must data be retained?
  • What latency targets are required?
  • What is the expected growth rate?

9. Security and Reliability in System Design

A scalable application is not a successful application if it exposes user information or loses important business data.

Security Considerations

  • Authentication: Verify the identity of users and services.
  • Authorization: Check whether a user is allowed to perform an operation.
  • TLS: Encrypt data in transit.
  • Encryption at Rest: Protect sensitive stored information.
  • Secrets Management: Avoid storing passwords, API keys, and private keys in source code.
  • Input Validation: Validate requests at system boundaries.
  • Rate Limiting: Control abusive traffic.
  • Audit Logging: Maintain appropriate records of important business and security events.

Reliability Considerations

  • Health checks and readiness probes.
  • Database backups and tested restoration procedures.
  • Replication and failover planning.
  • Timeouts, retries, and circuit breakers.
  • Dead-letter queues for failed event processing.
  • Disaster recovery plans.
  • Monitoring and alerting.

Observability

Observability helps engineers understand what is happening inside a running system.

Three important pillars are:

  • Logs: Records of application events and errors.
  • Metrics: Numerical measurements such as request rate, latency, CPU, memory, and error rate.
  • Traces: Show how a request travels across services.

Common tools include Prometheus, Grafana, OpenTelemetry, ELK/EFK stacks, and distributed tracing platforms.

10. Important System Design Trade-Offs

There is rarely one perfect architecture. Most real-world decisions involve trade-offs.

Decision Benefit Trade-Off
Horizontal scaling More processing capacity Distributed coordination
Caching Lower read latency Stale data and invalidation
Replication Read capacity and redundancy Replication lag and failover complexity
Sharding Distributed data capacity Complex queries and rebalancing
Microservices Independent deployment and scaling Network and operational complexity
Asynchronous processing Decoupled background work Eventual consistency and recovery handling
Strong consistency Stronger guarantees for critical data Potential latency or availability trade-offs

11. How to Approach a System Design Interview

One mistake candidates make is jumping directly into drawing microservices and selecting databases.

A better approach is to understand the problem first.

Step 1: Clarify Requirements

Ask questions about the application's users, features, traffic, data, and business rules.

Step 2: Define Functional Requirements

Identify what the system must do. Keep the first version focused on the most important user journeys.

Step 3: Define Non-Functional Requirements

Discuss availability, consistency, latency, scalability, durability, security, and recovery requirements.

Step 4: Estimate Traffic and Storage

Make reasonable assumptions and show your calculations. Exact numbers are less important than a clear estimation method.

Step 5: Design APIs and Data Models

Define the main endpoints, entities, relationships, indexes, and important constraints.

Step 6: Draw the High-Level Architecture

Identify the client, gateway, application services, databases, caches, and message brokers.

Step 7: Identify Bottlenecks

Think about database hotspots, slow external dependencies, high traffic, large payloads, and expensive operations.

Step 8: Discuss Failure Scenarios

Explain what happens when a database, service, broker, or external provider becomes unavailable.

Step 9: Explain Trade-Offs

Justify why you selected one approach over another. Interviewers want to understand your reasoning, not just hear technology names.

Step 10: Improve the Design

Discuss how the system could evolve as traffic, business requirements, and operational complexity increase.

12. Top System Design Interview Questions and Answers

Q1. What is the difference between scalability and availability?

Answer: Scalability is the ability to handle increasing workload by adding resources or improving efficiency. Availability is the ability of a system to remain accessible and operational when users need it.

Q2. What is the difference between horizontal and vertical scaling?

Answer: Vertical scaling increases the resources of an existing machine, while horizontal scaling adds more machines or instances. Horizontal scaling is common in distributed applications, but it introduces coordination and data consistency challenges.

Q3. Why do we need a load balancer?

Answer: A load balancer distributes incoming requests across multiple servers. It helps avoid overloading one instance and can route traffic away from unhealthy instances when configured with appropriate health checks.

Q4. What is the difference between a cache and a database?

Answer: A database is generally the primary persistent data store, while a cache stores selected data for faster access. Caches often have limited memory and require expiration, eviction, and invalidation strategies.

Q5. What is cache invalidation?

Answer: Cache invalidation is the process of removing or updating cached data when the underlying data changes. Common techniques include TTL expiration, explicit eviction, and event-driven invalidation.

Q6. What is the difference between SQL and NoSQL?

Answer: SQL databases generally use relational tables and SQL queries with strong transaction capabilities. NoSQL is a broad category of databases with different data models, such as documents, key-value pairs, wide columns, and graphs. Selection depends on data access patterns and requirements.

Q7. What is database sharding?

Answer: Sharding partitions data across multiple database nodes. Each node stores a portion of the overall dataset. It can improve capacity and distribute load, but introduces partitioning, rebalancing, and cross-shard query complexity.

Q8. What is database replication?

Answer: Replication maintains copies of data on multiple database nodes. It can improve read capacity and resilience. Depending on the replication mode, replicas may temporarily lag behind the primary.

Q9. What is eventual consistency?

Answer: Eventual consistency allows replicas to temporarily contain different values, with the expectation that they converge after updates have been propagated and no new changes occur.

Q10. What is the CAP theorem?

Answer: CAP describes the trade-off between consistency and availability when a network partition occurs in a distributed system. Partition tolerance is necessary when the system must operate across unreliable networks.

Q11. What is a message broker?

Answer: A message broker enables producers and consumers to exchange messages asynchronously. It decouples services and supports background processing. Examples include Apache Kafka and RabbitMQ.

Q12. What is the difference between Kafka and RabbitMQ?

Answer: Kafka is a distributed event streaming platform built around durable, partitioned event logs. RabbitMQ is a message broker supporting routing, queues, acknowledgements, and different messaging patterns. The choice depends on ordering, replay, routing, throughput, and operational requirements.

Q13. What is an API Gateway?

Answer: An API Gateway provides a common entry point for client requests and can handle routing, authentication integration, rate limiting, and request transformation.

Q14. What is a circuit breaker?

Answer: A circuit breaker prevents repeated calls to a failing dependency. It generally uses closed, open, and half-open states to control requests and test recovery.

Q15. What is the Saga pattern?

Answer: Saga coordinates a distributed business transaction through multiple local transactions. If a step fails, compensating actions are performed to handle the business consequences of earlier successful steps.

Q16. What is idempotency?

Answer: Idempotency ensures that repeating an operation with the same identity does not create duplicate business effects. Idempotency keys are commonly used in payment, booking, and order APIs.

Q17. What is the difference between synchronous and asynchronous communication?

Answer: In synchronous communication, the caller waits for a response. In asynchronous communication, the caller can publish or submit work and continue while another component processes it later.

Q18. How do you prevent duplicate records during concurrent requests?

Answer: Use database constraints, atomic conditional updates, transactions, appropriate locking, and idempotency keys. Application-level checks alone are not sufficient to prevent race conditions.

Q19. What is a CDN?

Answer: A Content Delivery Network distributes cached content through edge locations closer to users. It reduces content delivery latency and load on the origin server.

Q20. What is the difference between authentication and authorization?

Answer: Authentication verifies who a user is. Authorization determines what that authenticated user is permitted to do.

Q21. What is a single point of failure?

Answer: A single point of failure is a component whose failure can make a critical part of the system unavailable. Redundancy, failover, replication, and fault isolation help reduce this risk.

Q22. What is a dead-letter queue?

Answer: A dead-letter queue stores messages that could not be processed successfully after configured attempts or under defined failure conditions. It supports investigation and controlled reprocessing.

Q23. What is backpressure?

Answer: Backpressure is a mechanism that prevents a producer from overwhelming a slower consumer. It may involve limiting demand, controlling queues, rejecting requests, or reducing production rates.

Q24. What is the difference between latency and throughput?

Answer: Latency measures the time required to complete an operation. Throughput measures how many operations a system can process in a given period. A system can have high throughput but still have poor latency for individual requests.

Q25. How would you design a system for millions of users?

Answer: I would first clarify the functional and non-functional requirements, estimate traffic, and identify critical data flows. Then I would design APIs, data models, load balancing, caching, database scaling, and asynchronous processing. I would also address failure handling, security, monitoring, and cost. The final architecture would depend on actual workload and consistency requirements rather than assuming every component needs to be a microservice.

13. Common System Design Mistakes

  • Starting with technology: Selecting Kafka, Redis, or Kubernetes before understanding the problem.
  • Ignoring requirements: Designing a solution without clarifying business behavior.
  • Overengineering: Introducing microservices and distributed infrastructure without a real need.
  • Ignoring failures: Assuming every network call and database operation will succeed.
  • Ignoring data consistency: Using eventual consistency for operations that require stronger guarantees.
  • Ignoring security: Treating authentication, authorization, and data protection as afterthoughts.
  • Ignoring operations: Designing an architecture without considering deployment, monitoring, backups, and recovery.
  • Not explaining trade-offs: Listing technologies without explaining why they are suitable.

14. System Design Learning Roadmap

If you are a beginner, do not try to learn everything in one day. Build your understanding in stages.

Stage 1: Backend Fundamentals

  • HTTP, HTTPS, DNS, TCP/IP
  • REST APIs and API design
  • SQL, joins, indexes, and transactions
  • Basic networking and Linux
  • Application architecture

Stage 2: Core System Design

  • Load balancing
  • Caching with Redis
  • Database replication and sharding
  • CDN and rate limiting
  • Message queues and event-driven architecture

Stage 3: Distributed Systems

  • CAP theorem and consistency models
  • Idempotency and concurrency
  • Distributed transactions and Saga
  • Circuit breakers and retries
  • Partitioning and fault tolerance

Stage 4: Advanced Architecture

  • Microservices and service boundaries
  • Event-driven architecture
  • Observability and distributed tracing
  • High availability and disaster recovery
  • Capacity planning and performance optimization

Stage 5: Practice Real System Design Problems

  • Design a URL shortener.
  • Design a movie ticket booking platform.
  • Design a food delivery application.
  • Design a notification service.
  • Design a chat application.
  • Design a file storage service.
  • Design a video streaming platform.
  • Design a rate limiter.
  • Design an e-commerce order management system.

15. Final Thoughts

System design is not about using the maximum number of technologies or creating the most complicated architecture. It is about understanding a problem and making sensible engineering decisions.

A beginner should focus on understanding how requests move through an application, how data is stored, and why caching, load balancing, and databases are needed.

An experienced developer should go further. Think about concurrency, consistency, failure recovery, distributed transactions, service boundaries, observability, and the cost of operating the system.

One useful habit is to take a familiar application and ask yourself: What happens if the number of users becomes ten times higher? What if the database becomes unavailable? What if two users perform the same operation simultaneously? What if an external service responds slowly?

These questions gradually develop the mindset required to design reliable software.

Remember: Good system design is not about predicting every possible problem. It is about making the important decisions explicit, understanding their trade-offs, and building a system that can evolve as requirements change.


Keep Learning with D.Tech Academic

If you found this article useful, share it with a developer who is preparing for backend or system design interviews.