Stateless vs Stateful Services

Stateless services do not retain client-specific state between requests, while stateful services persist session or workflow state. The choice affects scalability, availability, and operational comple

Stateless vs Stateful Services#

Stateless services do not retain client-specific state between requests, while stateful services persist session or workflow state. The choice affects scalability, availability, and operational complexity.

Stateless Services#

Benefits:

  • Horizontal scaling is straightforward.
  • Failover is simple because any instance can serve any request.
  • Deployment and autoscaling are low-risk.

Tradeoffs:

  • Requires external state stores.
  • May increase latency due to extra lookups.

Stateful Services#

Benefits:

  • Lower latency when state is local.
  • Simplifies complex workflows that rely on in-memory state.

Tradeoffs:

  • Harder to scale and fail over.
  • Requires session affinity or sticky routing.
  • More complex deployment strategies.

Spring Boot Example: Externalized Session State#

1
2
3
4
@Configuration
@EnableRedisHttpSession
public class SessionConfig {
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RestController
@RequestMapping("/cart")
public class CartController {
    @PostMapping("/items")
    public ResponseEntity<Void> addItem(HttpSession session) {
        List<String> items = (List<String>) session.getAttribute("items");
        if (items == null) {
            items = new ArrayList<>();
        }
        items.add("item-1");
        session.setAttribute("items", items);
        return ResponseEntity.ok().build();
    }
}

Summary#

Stateless services are easier to scale and operate, while stateful services can offer lower latency for specific workflows. Externalizing state often provides the best balance for modern cloud architectures.

Contents