AlgoViz

Fallbacks

medium 30 min

A 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.

Video lesson · Chapter 1 of 5

The museum guide loses its headset

0:00 / 3:32

Fallbacks in 85 seconds

1:25Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A fallback is another way to answer when the main way fails. The user gets something useful, perhaps older, simpler or less personal, instead of an error page.

Graceful degradation is the plan behind it: the core of the product keeps working while extras disappear. Which parts are core and which are extras is a product decision, made before the failure.

Why it exists

A page that needs ten services fails when any of them fails, unless some are allowed to be missing. A fallback takes a service out of the list of things that must work.

It also protects the others: a caller with a plan B gives up early and frees its threads, instead of waiting and retrying. But a fallback is code and capacity too. If it is used for the first time in an outage, it may fail, or make the outage larger.

A short history

  1. 2003

    Steven Champeon and Nick Finck present progressive enhancement for web pages, as an evolution of the older strategy called graceful degradation.

  2. 2010

    RFC 5861 defines stale-if-error, which lets a cache answer with an old copy when the origin fails.

  3. 2012

    Hystrix matures inside Netflix and is released as open source. Each of its commands can have a fallback.

  4. 2019

    The AWS Builders' Library publishes Avoiding Fallback in Distributed Systems, with the story of a fallback that turned a small failure into a site outage around 2001.

  5. 2020

    RFC 8767 allows DNS resolvers to serve stale data when the authoritative servers cannot be reached.

Words to know

Primary
The first choice: the fresh, full answer.
Fallback chain
Sources tried in order until one answers.
Graceful degradation
Less, instead of nothing. The core stays up.
Stale data
A copy that was right at some earlier time.
Static fallback
An answer prepared in advance that needs no other system.
Failover
Doing the same work on another copy. The answer is as good as before.
Bimodal system
One that behaves differently in failure, in a mode that is rarely used.
Exercise
To run the fallback regularly in normal times.

How it works

Step through the idea, or press Play.

Step 1 of 3

Sort the features. Core or extra, and how wrong may it be?

Understand it

Start here

Sunday breakfast

Imagine a family that has rolls from the bakery every Sunday. One Sunday the bakery is closed. Breakfast is not cancelled. But what they do, and what they refuse to do, is worth a look.

Sam and Noor have breakfast
BAKERY AOPENBAKERY BOPENFREEZERTIN

Breakfast, the core, happened every time. How good it was changed.

What you gain

  • A better experience during a failure
  • Higher availability of the page
  • Graceful degradation instead of error pages
  • Less cascading: callers give up early
  • Tolerance of faults in optional parts

What you must think about

  • Old data that people may act on
  • More code and more states
  • Tests for paths that are rarely used
  • Monitoring, because users no longer complain
  • What people expect to see

Kinds

Four kinds of fallback, and a fifth

KindWhat it doesExampleBest for
Default valueA sensible value prepared in advance{ items: [], total: 0 }Optional data, non-critical features
Cached dataThe last good answer, even if it is oldstore.get(key), with its ageCatalogues, configuration, articles
Alternative serviceThe same question to somebody elsebackupApi.fetch()Critical paths, several regions, a second provider
Degraded responsePart of the answer, or a simpler one{ basic: true, features: [] }Tiered pages, feature flags
Honest errorSays what does not work, and what to do"Balance cannot be shown right now"Everything that must be right
An empty list is an answer too. Make sure that "no reviews yet" and "reviews cannot be loaded" look different.

A four-step chain

Try, and on failure fall to the next. The last one must not be able to fail.

Strategies

Chain, parallel, static

  1. 1

    Fallback chain

    One after the other: primary, backup, cache, default. Cheap in good times. The time of every failed step adds up.

  2. 2

    Parallel

    Ask primary and backup together and use the first success. Fast, but twice the load, so only for small, safe reads.

  3. 3

    Static

    An answer that lies ready in the program or on a CDN. The quickest and the most reliable.

TypeScript
await Promise.race([primary(), backup()]);   // the first to finish, even if it failedawait Promise.any([primary(), backup()]);    // the first to succeed
A common mistake is to use race. If primary fails quickly, race fails as well, although backup would have answered. Use any.

A chain must fit its budget

0.5+0.5+0.01=1.01 s;≤;1.2 s0.5 + 0.5 + 0.01 = 1.01 \text{ s} ;\le; 1.2 \text{ s}
Two attempts with a limit of 0.5 s and a cache with 0.01 s. If the budget is 0.8 s, skip the backup and go to the cache. Timeouts and their limits decide how deep a chain can be.

What a second source is worth

1−(1−0.995)(1−0.99)=1−0.005×0.01=0.999951 - (1 - 0.995)(1 - 0.99) = 1 - 0.005 \times 0.01 = 0.99995
99.5% and 99% together give 99.995%, if they fail independently. Two services on the same database, in the same zone or with the same bug fail together, and then this number means nothing.

Picture

One product page and its sources

Four sources in order

Users reach the product page machine, which also holds a default answer inside. It asks first the primary catalog, then the backup catalog, then a cache of last good answers.
The default lives inside the page's own machine, so nothing else can take it away.

The same chain in time

With a cache miss the last step would be the default: title unknown, details are coming back.

Stale

An old answer, on purpose

Age of the copyNormal timesWhen the source is down
Below the fresh limit, for example 1 minuteUse itUse it
Between fresh and stale limits, 1 minute to 1 dayFetch a new oneUse it, and say its age
Above the stale limitFetchNext fallback
Two limits, not one. The old code deleted entries after 5 or 10 minutes, so in an outage of 15 minutes the fallback store would be empty.
Text
Cache-Control: max-age=60, stale-if-error=86400
HTTP can do it for you: fresh for a minute, and for a day more if the origin fails. API caching explains the headers.

Degrade

The core stays

A shop, all well

  • Personal recommendations
  • Stock in real time
  • Dynamic prices
  • Customer reviews

The same shop, degraded

  • A list of popular items
  • Last known stock, checked again at checkout
  • Standard prices from the last valid list
  • No reviews, and a line that says so

Browsing and checkout must work. Recommendations and reviews may go. Note the second half of each line: an old stock number may be shown, but the order must check the real one, or you sell what you do not have.

Which fallback is acceptable?

FeatureAcceptableNot acceptableBecause
Product catalogueCached data, old is finePrice 0, "Unknown product"The old code's default sold at price 0
RecommendationsPopular items, or an empty placeAn error pageExtra
Search resultsCached, partial or popular results"0 results" without a reasonPeople believe it
Account balanceNone. At most a dated last value, for reading onlyA default, or 0Must be accurate
PermissionsDeny, or a short-lived cached yes for low riskAllow allFail closed
PaymentPending, queued, if the business agreesReport successMoney
Feature flagsThe last known set, then built-in defaultsA call on each requestConfiguration should survive its server

Choosing a fallback

Danger

A fallback that makes it worse

The cache fails, and the fallback is the database

The shop normally gets 950 of 1,000 reads a second from a cache and 50 from the database. The cache is down, so all 1,000 reads a second go to the database, which is overloaded.
It worked in every test, because the tests had little traffic.

Do the multiplication

1000×5%=50 reads/s;⟶;1000 reads/s×201000 \times 5\% = 50 \text{ reads/s} ;\longrightarrow; 1000 \text{ reads/s} \qquad \times 20
A hit rate of 95% hides 19 of 20 reads from the database. If the cache disappears, the database sees 20 times its normal load.

The AWS Builders' Library tells such a story from about 2001: when caches for shipping speeds failed, web servers asked the database directly. It locked up, the whole site went down, and fulfilment, which used the same database, as well. A missing line of text would have been the better fallback.

Four safer ways

  1. 1

    Improve the primary

    Two replicas that are both used beat one primary and one path that nobody uses. See achieving high availability.

  2. 2

    Let the caller decide

    Return a clear error. The caller knows better than you whether the part is optional.

  3. 3

    Push data in advance

    If the data is already on the machine, there is no remote call that can fail at request time.

  4. 4

    Use the second path all the time

    Send a share of normal traffic through it. Then it is tested, warm and sized.

Afterwards

Coming back

A fallback ends too, and the way back needs a plan: warm the cache before all readers return, work through what was queued as pending at a limited pace, and tell people that the full service is back.

Three modes of one feature

Recovering is a mode of its own: a share of traffic goes to the primary, and the rest still uses the fallback.

Best practice

Five rules

  • Clear order

    Sort sources by freshness and by how likely they are to work. Different failures need different plans.

  • Track the use

    Count answers by source. Users stop complaining when fallbacks work, so the count is your only alarm.

  • Test regularly

    Force the failure in tests, in drills, and for a small share of real traffic.

  • Say it

    "As of 10:40", "reviews are coming back". People forgive old, not wrong.

  • Keep it simple

    Fewer dependencies than the primary. Best: none.

Where the fallback sits

PlaceExampleGood for
Browser or appShow the last list from the deviceOffline reading
CDNA static copy of the page, stale-if-errorThe whole site during an origin outage
GatewayA fixed JSON answer when a route's breaker is openSimple, shared rules
Calling servicePopular items instead of personal onesIt knows what the part means. Usually the best place

What triggers a fallback is a failure, a timeout, or an open circuit breaker. Where the fallback stands among the other protections is in resilience: outermost, around the retries.

Summary

The whole topic in one minute.

For each dependency write down what the user gets without it. Optional parts get older data, popular items or nothing. Core parts get another copy of the same thing. Money, stock at the moment of sale, permissions and health data get an honest error.

Keep the fallback simpler than what it replaces, give it enough capacity, label its answers, count its use, and run it on purpose. A path that nobody has walked is not a way out.

  • Decide per feature, before the failure, what the user gets.
  • Primary, another copy, older data, simpler data, default, honest error.
  • Never invent a balance, a price, a permission or a success.
  • Two age limits: fresh and stale. Say the age.
  • A fallback needs capacity, labels, counts and practice.

Sources