Fallbacks
medium 30 minA fallback is the answer you give when the first choice fails: a backup service, an older copy, a simpler result, a default, or an honest error.
See it run
What the user gets when the first choice fails, and how plan B can hurt.
Operations
The fallback chain
Three switches: primary fails, backup fails, cache miss. Each outcome is a step.
Step 1 of 5
Primary answers
Source: primary
Fresh data from the primary. Nothing else is asked.
Step 1: Primary answers
for i, source in enumerate([primary, backup, cache, default]): try: value = source() return value, source.name, i > 0 # was it a fallback? except Failed: continue- Good for
- Optional parts
- Costs
- Time per failed step
- No chain
- an error page
Return the source together with the value. Otherwise nobody knows what is being served.
In the real world
The same fallbacks doing real jobs. Pick one and step through it.
The account database cannot be reached.
Step 1 of 3
Healthy
250.00
The balance is read from the accounts.
Step 1: Healthy
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A default that looks real
criticalThe old code returned price 0 and "Unknown product". Somebody can buy it.
Wrongreturn Product(id, "Unknown Product", price=0)Rightreturn ProductView(id, complete=False) # no price, no buy buttonA cache miss taken for success
majorcache.get returned None, and the chain called that an answer.
Wrongchain.add(lambda: cache.get(key))Rightvalue = cache.get(key)if value is None: raise Failed("miss")A coroutine taken for a value
majorIn the old Python chain a lambda returned a coroutine that nobody awaited. It counted as success.
Wrongresult = strategy() # a coroutine objectRightresult = strategy()if inspect.isawaitable(result): result = await resultUnlimited plan B
criticalIt takes down something that was healthy.
Wrongexcept CacheDown: return db.get(key)Rightif db_limit.try_acquire(): return db.get(key)return stale_copy(key)
Interview tips
How to explain it
- Core and extras.
- The next best honest answer.
- Labelled, counted, practised.
Memory trick: PCDE
- Primary, Copy.
- Degraded.
- Empty or Error.
Ask of each fallback
- Can it be wrong in a way that hurts?
- Can it take the load?
- When was it last used?
Never fall back to
- An invented price or balance.
- Allow all.
- A success that did not happen.