THINK FIRST·CODE LATER

← All labs

Resilient tutor: fallback and circuit breaker

Problem

Implement Buddy's resilience layer with dependency inversion. Define an interface Tutor with String answer(String question) throws Exception, and two implementations simulating providers. Then write a ResilientTutor that uses a primary and a secondary tutor with a circuit breaker on the primary.

Input: lines P S question... until the end of input, where P and S are the status of the primary and secondary provider for that request: UP (answers) or DOWN (throws an exception).

Behaviour for each question:

  1. If the breaker is open, skip the primary (it counts one skipped request). After 2 skipped requests the breaker becomes half-open: the next request tries the primary once.
  2. Otherwise try the primary. If it answers, print [primary] <question> and reset the failure count (breaker closed). If it fails, count a consecutive failure; after 3 consecutive failures — or after a failed half-open trial — the breaker opens (and the skip counter starts at 0).
  3. If the primary was skipped or failed, try the secondary: [secondary] <question>; if it also fails print [offline] Buddy is offline - please post "<question>" on the board.

After each line, if the breaker changed state, print breaker: OLD -> NEW (states CLOSED, OPEN, HALF_OPEN). At the end print Primary: a, Secondary: b, Offline: c.

Input:

DOWN UP q1
DOWN UP q2
DOWN DOWN q3
UP UP q4
UP UP q5
UP UP q6

Output:

[secondary] q1
[secondary] q2
[offline] Buddy is offline - please post "q3" on the board
  breaker: CLOSED -> OPEN
[secondary] q4
[secondary] q5
  breaker: OPEN -> HALF_OPEN
[primary] q6
  breaker: HALF_OPEN -> CLOSED
Primary: 1, Secondary: 4, Offline: 1

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.