Fail-Fast
Fail-Fast — Fall over loudly, fall over quickly
"A program that fails fast is better than a program that silently does the wrong thing." — Jim Shore, Fail Fast (IEEE Software, 2004)
Core idea
When the program state becomes invalid, stop immediately at the nearest boundary with a loud error. Do not try to "rescue" the situation. That only hides the bug and pushes it further down the stack, where it will cost 10× more to debug.
Why it matters
| If you swallow the error | If you fall over right away |
|---|---|
| The bug shows up somewhere else | Point of failure = point of cause |
| The stack trace points to the wrong place | The stack trace points to the actual culprit |
| Data often gets corrupted | Data stays consistent |
| The user gets a wrong result | The user gets a clear error |
| The bug hides in logs for months | The bug shows up in CI or the first test |
A general engineering rule: letting invalid data propagate is the most expensive kind of bug. The point of effect is far from the point of cause.
Example 1: silent vs loud
❌ Bad (defensive, "protect against everything")
def get_discount(customer) -> float:
if customer is None:
return 0 # quietly return something
if not hasattr(customer, "tier"):
return 0
if customer.tier == "gold":
return 0.15
return 0 # for any unknown tier
What is wrong here:
customer is Noneis a bug higher up the stack. Hiding it lets that bug show up somewhere else.- An unknown
tier? We quietly compute 0. A year later you discover that customers withtier="platinum"were not getting their discount.
✅ Good (fail-fast)
ALLOWED_TIERS = {"gold", "silver", "bronze"}
def get_discount(customer: Customer) -> float:
if customer is None:
raise ValueError("customer is required")
if customer.tier not in ALLOWED_TIERS:
raise ValueError(f"unknown tier: {customer.tier!r}")
return {"gold": 0.15, "silver": 0.10, "bronze": 0}[customer.tier]
Now:
- If someone calls it with
None, you see immediately who and from where. - A new tier? CI breaks, the test goes red, and you add support for it consciously.
Example 2: validation at the boundary vs everywhere
❌ Bad (paranoia on the inside)
def calculate_total(items: list) -> float:
if items is None: return 0
if not isinstance(items, list): return 0
total = 0
for item in items:
if item is None: continue
if not hasattr(item, "price"): continue
if item.price is None: continue
if item.price < 0: continue
total += item.price
return total
The inner function trusts nothing. This is a DRY violation (the same check repeated everywhere) and it also hides bugs.
✅ Good (validate at the boundary, trust on the inside)
# System boundary: inputs are not yet trusted here
def parse_items_from_json(raw: str) -> list[Item]:
data = json.loads(raw)
items = []
for entry in data:
if "price" not in entry:
raise ValueError(f"missing 'price' in item: {entry}")
price = float(entry["price"])
if price < 0:
raise ValueError(f"negative price: {price}")
items.append(Item(price=price))
return items
# Inner function: trusts the types, does not re-validate
def calculate_total(items: list[Item]) -> float:
return sum(i.price for i in items)
The principle:
[ outside world ] → [ VALIDATION — fail-fast ] → [ trusted zone ]
Example 3: the delayed crash
❌ Bad
def init():
config_path = os.environ.get("CONFIG_PATH") # may be None
return Service(config_path)
class Service:
def __init__(self, config_path):
self.config_path = config_path
def handle_request(self, req):
config = json.load(open(self.config_path)) # crashes HERE, hours after startup
...
The service starts without CONFIG_PATH and everything looks fine. Six hours later, the first request gets TypeError: expected str, got None. You debug backwards from there.
✅ Good
def init():
config_path = os.environ.get("CONFIG_PATH")
if not config_path:
raise RuntimeError("CONFIG_PATH env var is required")
if not os.path.isfile(config_path):
raise RuntimeError(f"config file not found: {config_path}")
return Service(config_path)
The service either does not start at all, or it works correctly. The error appears in 0.1 seconds, right in the logs.
Example 4: assert for inner invariants
def withdraw(account: Account, amount: float) -> None:
if amount <= 0:
raise ValueError("amount must be positive") # INPUT check
account.balance -= amount
assert account.balance >= 0, f"balance went negative: {account.balance}"
# ↑ INVARIANT — a state that should never be broken
ValueErroris for inputs that the caller can get wrong.assertis for invariants that our own code must preserve. A failed assert means a bug in our code.
⚠️ In Python, assert is disabled with the -O flag. So business validation uses raise, not assert. assert is only for inner invariants and tests.
Fail-Fast vs Graceful Degradation
Not every system should crash. Some places have to "carry on":
- UI applications — better to show "loading failed" than a blank screen.
- Batch processors — 999 out of 1000 records processed; one bad record should not stop the rest (but it must be logged, never swallowed).
- Independent microservices — crashing the whole thing because one service is unavailable is bad.
Rule:
- At the system boundary — fail-fast (input validation, config, DB connection).
- Inside the core — fail-fast (invariants, types, preconditions).
- At the user-facing output — graceful (catch the error, show a friendly message, log the cause).
The worst anti-patterns
1. Bare except:
try:
do_something()
except:
pass # ← hides EVERYTHING, including KeyboardInterrupt and SystemExit
except Exception: is softer, because KeyboardInterrupt and SystemExit inherit from BaseException, not Exception. But it is still an anti-pattern: it catches programmer mistakes (AttributeError, KeyError, TypeError) and hides them.
This is called "error swallowing" — the most expensive kind of bug.
2. Returning "nothing" instead of an error
def parse_number(s: str) -> int:
try:
return int(s)
except ValueError:
return 0 # ← silently returns 0, the caller thinks everything is fine
3. Logging instead of crashing on a critical error
if not config:
logger.warning("config missing, using defaults")
config = {}
"Defaults" may lead to wrong behaviour. Better to crash than to keep going incorrectly.
Rules of thumb
- Check preconditions at the entry, raise
ValueError/TypeErrorwith a clear message. - Check config at startup, not "when it becomes needed".
assertis for invariants only, not for business validation.- Never write
except:without a type. Catch specific exceptions. - If you catch, either handle or re-raise with context (
raise ... from e). - Strict at the boundary, trusting on the inside. Do not duplicate validation.
One-line summary
Invalid state should fall over immediately and loudly. The point of cause is the point of failure.