7
← Back to Pattern Arsenal
behavioral

Chain of Responsibility

must know

Stage 1: Problem

The Problem

You are building an API gateway for a microservices platform. Every incoming HTTP request must go through several checks before reaching the actual handler:

  1. Rate limiting — reject if the client exceeded their quota
  2. Authentication — verify the JWT token is valid
  3. Authorization — check if the user has permission for this endpoint
  4. Request validation — validate the request body against a schema
  5. Logging — log the request details for observability

Different endpoints need different combinations: public endpoints skip auth, internal endpoints skip rate limiting, admin endpoints need extra authorization.

Right now, the code looks like this:

typescript
1class ApiGateway {
2 async handleRequest(req: Request, res: Response) {
3 // Rate limiting
4 const clientIp = req.ip;
5 const count = await this.redis.incr(`rate:${clientIp}`);
6 if (count > 100) {
7 return res.status(429).json({ error: 'Rate limited' });
8 }
9
10 // Auth
11 const token = req.headers.authorization?.split(' ')[1];
12 if (!token) {
13 return res.status(401).json({ error: 'No token' });
14 }
15 const user = this.jwt.verify(token);
16
17 // Authorization
18 const endpoint = req.path;
19 const allowed = await this.permissionService.check(user.role, endpoint);
20 if (!allowed) {
21 return res.status(403).json({ error: 'Forbidden' });
22 }
23
24 // Validation
25 const schema = this.getSchema(endpoint);
26 if (schema) {
27 const result = schema.safeParse(req.body);
28 if (!result.success) {
29 return res.status(400).json({ error: result.error });
30 }
31 }
32
33 // Logging
34 console.log(`[${new Date().toISOString()}] ${req.method} ${req.path} user=${user.id}`);
35
36 // Finally, the actual handler
37 const handler = this.getHandler(endpoint);
38 return handler(req, res);
39 }
40}

Think about it: What happens when you need different combinations of these checks for different endpoints? What if you need to add a new check (e.g., CORS, content-type validation)?


1 / 10 — Problem