Problem · Array

Circuit Breaker Database Failover

Learn this problem
MediumDatabricks logoDatabricksFULLTIMEPHONE SCREEN

Problem statement

A service sends requests to a database cluster with a PRIMARY, REPLICA_1, and REPLICA_2. Each server has an independent circuit breaker that starts CLOSED.

The input outcomes contains one row per request. Each row has exactly three values in server order: primary, replica 1, and replica 2. A value is either SUCCESS or FAILURE and describes what would happen if that server were attempted for that request.

Process requests in order. For each request:

  1. Consider the servers in the fixed order PRIMARY, REPLICA_1, REPLICA_2.
  2. Skip a server whose breaker is OPEN.
  3. Attempt each remaining server until one succeeds. A success resets that server's consecutive-failure count to 0 and completes the request.
  4. A failure increments only that server's consecutive-failure count. When the count reaches 2, its breaker becomes OPEN permanently for the rest of the batch. Continue to the next server for the same request.

Return one result per request: the name of the server that succeeded, or FAILED if every server is open or fails.

Function

routeDatabaseRequests(outcomes: String[][]) → String[]

Examples

Example 1

outcomes = [["FAILURE","SUCCESS","SUCCESS"],["FAILURE","FAILURE","SUCCESS"],["SUCCESS","SUCCESS","SUCCESS"],["FAILURE","FAILURE","SUCCESS"]]return = ["REPLICA_1","REPLICA_2","REPLICA_1","REPLICA_2"]

The primary fails twice and opens during the second request. Later requests skip it. Replica 1 succeeds on requests one and three, while replica 2 handles requests two and four.

Example 2

outcomes = [["FAILURE","FAILURE","FAILURE"],["SUCCESS","SUCCESS","SUCCESS"],["FAILURE","FAILURE","FAILURE"],["FAILURE","SUCCESS","SUCCESS"],["SUCCESS","SUCCESS","SUCCESS"]]return = ["FAILED","PRIMARY","FAILED","FAILED","FAILED"]

The first request gives every server one failure. The primary then succeeds and resets. On the third request both replicas receive their second consecutive failure and open. The fourth request gives the primary its second consecutive failure, so all breakers are open from then on.

Example 3

outcomes = []return = []

No requests produce no routing results.

Constraints

  • 0 <= outcomes.length <= 10^5.
  • Every row has length 3.
  • Every value is SUCCESS or FAILURE.
  • All breakers start CLOSED with zero consecutive failures.

More Databricks problems

drafts saved locally
public String[] routeDatabaseRequests(String[][] outcomes) {
  // write your code here
}
outcomes[["FAILURE","SUCCESS","SUCCESS"],["FAILURE","FAILURE","SUCCESS"],["SUCCESS","SUCCESS","SUCCESS"],["FAILURE","FAILURE","SUCCESS"]]
expected["REPLICA_1", "REPLICA_2", "REPLICA_1", "REPLICA_2"]
checking account