Fail fast means you find an invalid state as early as possible and stop at once with a clear error. You don't carry on and fail later in a confusing place.
Examples:
- Check the configuration at startup. If
DATABASE_URLis missing, refuse to start. Don't wait to crash on the first request. - Validate request bodies at the API boundary, so bad input never reaches the domain (business logic) code.
- Put guard clauses (early checks that throw) at the top of functions and constructors. For example, a
Moneyvalue object rejects a negative amount when it is created. - Set timeouts on outgoing calls, so a dependency that hangs fails quickly.
- Treat unexpected states as bugs and throw. Don't return a default value that hides them.
The benefit: errors appear close to their cause, so they are cheaper to find and fix. Also, corrupt data never gets written.
- Find problems early and stop with a clear error.
- Validate config at startup and validate input at the API boundary.
- Use guard clauses and value objects that validate themselves.
- Set timeouts so slow dependencies fail quickly.
- Errors appear near their cause, and no corrupt data is written.
Read more