For every feature you ship, ask what happens to it when the database is down.
If the answer is "the whole request throws", you made an availability decision without noticing you were making one.
Define the capability as one small interface, pick the implementation based on what infrastructure is actually present, and decide on purpose whether each implementation fails open (keeps the feature working in a degraded mode) or fails closed when its dependency is gone.
The example in this article is a per-IP usage quota for anonymous users.
Availability Is a Per-Feature Design Choice
We tend to think of availability as an infrastructure number (four nines, load balancers, replicas).
But availability is also a design choice you make per feature, and you have to decide what "degraded" means before you need it.
For a per-IP quota on a free tier, degraded might mean "count per instance instead of globally". For a recommendation widget, degraded means "show bestsellers instead of personalized picks". For login, there is no acceptable degraded mode, and that is a legitimate answer too.
The pattern below makes the decision explicit and testable instead of implicit in a stack trace.
The Interface: No Storage Details
The capability is small: consume one unit of quota, or peek at the current state.
public interface IGuestQuota
{
Task<QuotaDecision> TryConsumeAsync(string partitionKey, CancellationToken ct);
Task<QuotaDecision> PeekAsync(string partitionKey, CancellationToken ct);
}
public sealed record QuotaDecision(
bool Allowed,
int Remaining,
DateTimeOffset ResetsAt);
The contract mentions no DbContext, connection string, Postgres, memory, or Redis.
Call sites depend on "a quota exists", not on where the count lives, which is what makes the backing store swappable at startup.
Implementation A: Durable and Cross-Instance (Postgres)
The primary implementation stores counters in Postgres: durable, shared across every instance, and correct under concurrency.
A naive implementation reads the count, checks it, and writes count + 1. Two concurrent requests both read 4, both decide "under the limit of 5", and both write 5. You just gave away a free unit, and under load you will give away many.
The fix is to make the atomic increment be the check, in one statement. The counters live in one table, keyed by day and partition:
CREATE TABLE quota_counters (
day DATE NOT NULL,
partition_key TEXT NOT NULL,
count INT NOT NULL,
PRIMARY KEY (day, partition_key)
);
The implementation uses EF Core with the Npgsql provider (dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL).
AppDbContext is the application's existing EF Core context; it needs no entity for this table because the quota runs raw SQL:
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
public sealed class QuotaOptions
{
public int DailyLimit { get; init; } = 5;
}
public sealed class PostgresGuestQuota(
IServiceScopeFactory scopeFactory,
QuotaOptions options) : IGuestQuota
{
public async Task<QuotaDecision> TryConsumeAsync(string partitionKey, CancellationToken ct)
{
var (day, resetsAt) = DayFor();
try
{
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// The atomic increment IS the check: one statement, no read-modify-write race
// between concurrent callers.
var rows = await db.Database.SqlQuery<int>(
$"""
INSERT INTO quota_counters (day, partition_key, count)
VALUES ({day}, {partitionKey}, 1)
ON CONFLICT (day, partition_key) DO UPDATE SET count = quota_counters.count + 1
RETURNING count AS "Value"
""").ToListAsync(ct);
return Decide(rows[0], resetsAt);
}
catch (Exception ex) when (ex is DbException or InvalidOperationException)
{
// FAIL OPEN: the store is unavailable; allow rather than 500. (This quota is a
// conversion nudge, not a security control. A security control would fail CLOSED.)
return Unenforced(resetsAt);
}
}
public async Task<QuotaDecision> PeekAsync(string partitionKey, CancellationToken ct)
{
var (day, resetsAt) = DayFor();
try
{
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var rows = await db.Database.SqlQuery<int>(
$"""
SELECT count AS "Value"
FROM quota_counters
WHERE day = {day} AND partition_key = {partitionKey}
""").ToListAsync(ct);
var used = rows.Count > 0 ? rows[0] : 0;
return new QuotaDecision(used < options.DailyLimit, Math.Max(0, options.DailyLimit - used), resetsAt);
}
catch (Exception ex) when (ex is DbException or InvalidOperationException)
{
return Unenforced(resetsAt);
}
}
private static (DateOnly Day, DateTimeOffset ResetsAt) DayFor()
{
var today = DateOnly.FromDateTime(DateTime.UtcNow);
var resetsAt = new DateTimeOffset(today.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
return (today, resetsAt);
}
private QuotaDecision Decide(int count, DateTimeOffset resetsAt) =>
new(count <= options.DailyLimit, Math.Max(0, options.DailyLimit - count), resetsAt);
private QuotaDecision Unenforced(DateTimeOffset resetsAt) =>
new(true, options.DailyLimit, resetsAt);
}
The INSERT ... ON CONFLICT DO UPDATE ... RETURNING (an upsert) increments and reads in a single round trip, and Postgres serializes concurrent updates to the same row for us.
Before reaching for distributed locking, ask whether you can design the race away with an atomic operation.
Implementation B: The Per-Instance Fallback
The fallback runs entirely in memory, for environments where no application database is configured (local dev, a lightweight deployment, or a conscious "we do not want the dependency" choice):
using System.Collections.Concurrent;
public sealed class InMemoryGuestQuota(QuotaOptions options) : IGuestQuota
{
private readonly ConcurrentDictionary<string, int> _counts = new();
private readonly Lock _dayLock = new();
private DateOnly _day = DateOnly.FromDateTime(DateTime.UtcNow);
public Task<QuotaDecision> TryConsumeAsync(string partitionKey, CancellationToken ct)
{
RollDayIfNeeded();
var count = _counts.AddOrUpdate(partitionKey, 1, (_, current) => current + 1);
var remaining = Math.Max(0, options.DailyLimit - count);
return Task.FromResult(new QuotaDecision(count <= options.DailyLimit, remaining, NextUtcMidnight()));
}
public Task<QuotaDecision> PeekAsync(string partitionKey, CancellationToken ct)
{
RollDayIfNeeded();
var used = _counts.GetValueOrDefault(partitionKey);
var remaining = Math.Max(0, options.DailyLimit - used);
return Task.FromResult(new QuotaDecision(used < options.DailyLimit, remaining, NextUtcMidnight()));
}
// Clear every counter when the UTC day changes.
private void RollDayIfNeeded()
{
var today = DateOnly.FromDateTime(DateTime.UtcNow);
if (today == _day)
{
return;
}
lock (_dayLock)
{
if (today != _day)
{
_counts.Clear();
_day = today;
}
}
}
private static DateTimeOffset NextUtcMidnight() =>
new(DateOnly.FromDateTime(DateTime.UtcNow).AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
}
This implementation has a weaker guarantee, and you should name it out loud: the count is per instance. Run three instances behind a load balancer and a determined client can get up to three times the budget. Restart the app and the counters reset.
For a free-tier nudge, that is fine. The quota still shapes behavior for most users, and the worst case is a few extra freebies. Write that tradeoff down, in the code review or the ADR, so the team knows it was a choice.
Capability-Based Selection at Startup
The last piece: choose the implementation from what infrastructure is actually present, and register it behind the one interface in Program.cs:
using Microsoft.EntityFrameworkCore;
var appDb = builder.Configuration.GetConnectionString("AppDb");
var hasAppDb = !string.IsNullOrWhiteSpace(appDb);
builder.Services.AddSingleton(new QuotaOptions { DailyLimit = 5 });
if (hasAppDb)
{
builder.Services.AddDbContext<AppDbContext>(options => options.UseNpgsql(appDb));
builder.Services.AddSingleton<IGuestQuota, PostgresGuestQuota>(); // durable, cross-instance
}
else
{
builder.Services.AddSingleton<IGuestQuota, InMemoryGuestQuota>(); // per-instance fallback
}
Every call site resolves IGuestQuota without knowing which one it got.
The feature works in every environment, from a laptop with zero infrastructure to a multi-instance production deployment, and the app gets the stronger guarantee once an AppDb connection string is configured.
Should a Feature Fail Open or Fail Closed?
Look back at the catch block in the Postgres implementation.
When the database is unreachable, the quota returns "allowed, unenforced" instead of throwing.
That is failing open: when the enforcement mechanism errors, the operation proceeds. The alternative is failing closed: when the mechanism errors, deny.
The same pattern demands opposite defaults depending on what the feature protects:
- A free-tier quota is a conversion nudge. If it breaks, handing out a few extra free requests costs cents. Turning every anonymous request into a 500 because a quota table was unreachable is a full outage for those users. Fail open.
- Authentication, authorization, a payment fraud check, a sandbox escape detector: if the mechanism errors, you deny. An attacker who can knock over your auth store must not get access because of it. Fail closed.
Choosing wrong in either direction is a bug, because a security control that fails open is a vulnerability, and a best-effort feature that fails closed turns a dependency failure into an outage.
You make that choice once, in the catch block, with a comment explaining it.
Test the Degraded Mode, or You Do Not Have One
This architecture makes the degraded paths trivially testable, because each one is an ordinary implementation behind an ordinary interface.
Write three tests:
[Fact]
public async Task InMemoryQuota_enforces_the_limit()
{
var quota = new InMemoryGuestQuota(new QuotaOptions { DailyLimit = 2 });
Assert.True((await quota.TryConsumeAsync("1.2.3.4", default)).Allowed);
Assert.True((await quota.TryConsumeAsync("1.2.3.4", default)).Allowed);
Assert.False((await quota.TryConsumeAsync("1.2.3.4", default)).Allowed);
}
First, the fallback implementation enforces the limit (above).
Second, the Postgres implementation fails open: point it at a connection string with a wrong port and assert that TryConsumeAsync returns an allowed, unenforced decision instead of throwing.
Third, the selection logic: boot the app with and without the connection string configured and assert which implementation got registered.
Don't skip the second test.
The fail-open catch block only runs during an outage, so without a test, the first time it executes is during a real one.
The Same Shape, Everywhere
The same pattern shows up in other places:
- FusionCache with no Redis configured degrades to a fully functional L1-only cache, and fail-safe serves stale data when the source is down. The capability stays up with a weaker guarantee.
- A distributed lock whose store is unreachable can degrade to unsynchronized execution for best-effort work, rather than failing the request.
- Fallback policies in Polly are the per-call version: a cheaper answer replaces the failed primary call.
- Rate limiting middleware backed by a distributed store faces the identical fail-open-or-closed fork.
Each case has one capability, multiple implementations with different guarantees, and an explicit decision about what happens when the strong one is unavailable. Building resilient cloud applications means making that decision feature by feature.
Summary
- Define capabilities as small interfaces that don't mention their backing store, so you can swap in a degraded implementation.
- Prefer designing races away with atomic operations (
ON CONFLICT ... RETURNING) over adding locks. - Ship a fallback implementation and be honest about its weaker guarantee (N instances means N times the budget).
- Select the implementation at startup from the infrastructure that is actually present.
- Decide fail-open vs fail-closed per feature, consciously: nudges fail open, security controls fail closed.
Frequently Asked Questions
What does graceful degradation mean in software?
Graceful degradation means a feature keeps working in a reduced mode when a dependency is unavailable, instead of failing entirely. A typical example is a per-IP quota that counts in a shared database when one is configured, counts per instance in memory when none is, and stops enforcing the limit instead of throwing when the database fails at runtime.
What is the difference between fail open and fail closed?
Fail open means allowing the operation when the enforcement mechanism errors; fail closed means denying it. Best-effort features like conversion nudges should fail open. Security controls like authentication and authorization must fail closed.
How do I avoid a read-modify-write race without a distributed lock?
Push the read-modify-write into a single atomic statement. In PostgreSQL, INSERT ON CONFLICT DO UPDATE with a RETURNING clause increments and reads a counter atomically, so concurrent callers serialize inside the database without any application-level locking.
Is an in-memory fallback safe when running multiple instances?
It works, but with a weaker guarantee: each instance keeps its own counter, so with N instances a client can get up to N times the intended budget. Name that tradeoff explicitly and decide whether it is acceptable for the feature.

