THN Interview Prep

Chain of Responsibility (Behavioral)

Intent / problem it solves

Pass a request along a chain of handlers until one handles it (or it drops). Decouples sender from receivers and lets you reorder or add handlers without changing client code.

When to use / when NOT

Use for middleware pipelines, approval workflows, filters, or validation chains.

Avoid when a fixed orchestrator or explicit routing is clearer; watch for hard-to-debug chains.

Structure

Handler interface defines successor link or abstract processing; concrete handlers either handle or forward.

Loading diagram…

Go example

package main

import "fmt"

type Request struct {
	Token string
}

type Handler interface {
	Handle(request Request) string
}

type AuthHandler struct{ Next Handler }

func (handler AuthHandler) Handle(request Request) string {
	if request.Token == "" {
		return "missing"
	}
	if handler.Next != nil {
		return handler.Next.Handle(request)
	}
	return "ok"
}

type RateHandler struct{ Next Handler }

func (handler RateHandler) Handle(request Request) string {
	if request.Token == "throttle" {
		return "rate"
	}
	if handler.Next != nil {
		return handler.Next.Handle(request)
	}
	return "ok"
}

func main() {
	chain := AuthHandler{Next: RateHandler{Next: nil}}
	fmt.Println(chain.Handle(Request{Token: "throttle"}))
}

JavaScript example

class TokenPipeline {
  constructor() {
    this.handlers = [];
  }

  use(handler) {
    this.handlers.push(handler);
    return this;
  }

  run(context) {
    for (const handler of this.handlers) {
      const outcome = handler(context);
      if (outcome) {
        return outcome;
      }
    }
    return 'pass';
  }
}

const pipeline = new TokenPipeline()
  .use((context) => (context.token ? null : 'missing'))
  .use((context) => (context.token === 'bad' ? 'rejected' : null));

console.log(pipeline.run({ token: 'bad' }));

Interview phrase

“Chain of responsibility models middleware: each link can handle or pass along, so I can add cross-cutting steps without entangling the client with every rule.”

Map to LLD for request filters, approval flows, or plugin chains in LLD case studies.

Last updated on

Spotted something unclear or wrong on this page?

On this page