Skip to content

Routing APIs

from sqlspec.config import ReplicaGroup
from sqlspec.core.routing import (
    RandomSelector,
    ReplicaHealthBreaker,
    ReplicaSpec,
    RoundRobinSelector,
)
from sqlspec.utils.routing import (
    RoutingContext,
    RoutingContextPayload,
    RoutingEntry,
    RoutingScope,
    SQLSpecRoutingMiddleware,
    sign_primary_pin,
    verify_primary_pin,
)

Use Read Replicas for setup and Replica Operations for freshness and failure policy. Context scopes select intent; database roles and policies still govern access and write permission.

RoutingContext.replica() requires a reader and never falls back to the primary. Missing replica groups or exhausted readers raise ReplicaUnavailableError. Automatic read providers retain configured fallback. Outside an active transaction, an explicit replica scope can override a historical primary pin; normal automatic routing remains pinned. A conflicting replica choice during a primary transaction raises an error.

Routing Context and ASGI Middleware

RoutingEntry

Immutable routing directive for a logical database bind.

Parameters:

Name Type Description Default
mode RoutingMode

Requested routing mode.

'auto'
replica_group str | None

Optional replica group name.

None
causal_token str | None

Adapter-specific causal consistency token.

None
max_staleness_seconds float | None

Maximum configured replica staleness.

None
pinned_by_write bool

Whether this directive follows a write.

False

RoutingContextPayload

Immutable snapshot of routing directives indexed by logical bind key.

RoutingScope

Bind a routing snapshot for a synchronous or asynchronous block.

RoutingContext

Access routing directives and bind request-local consistency scopes.

current
current()

Return the active routing snapshot, or None outside a scope.

get_entry
get_entry(bind_key=None)

Resolve the directive for a logical bind key.

mark_write
mark_write(bind_key=None, *, causal_token=None)

Pin an active scope to primary; return False for unscoped workers.

scope
scope(payload=None)

Create a sync/async scope, inheriting current directives by default.

primary
primary(bind_key=None, *, causal_token=None)

Create a scope explicitly routing a bind to primary.

replica
replica(
    bind_key=None,
    *,
    replica_group=None,
    causal_token=None,
    max_staleness_seconds=None,
)

Create a scope requesting a replica with optional consistency bounds.

auto
auto(bind_key=None)

Create a scope allowing automatic routing for a bind.

set
set(payload)

Bind a routing snapshot and return its restoration token.

reset
reset(token)

Restore the snapshot associated with a previous binding token.

clear
clear()

Clear routing state in the current execution context.

SQLSpecRoutingMiddleware

Bind ASGI request routing from cookies, headers, then a custom extractor.

sign_primary_pin

sign_primary_pin(
    secret,
    *,
    ttl_seconds=5.0,
    bind_key=None,
    causal_token=None,
    clock=time.time,
)

Create an expiring HMAC-SHA256 primary pin cookie value bound to bind_key.

Parameters:

Name Type Description Default
secret str | bytes

Shared HMAC secret key (non-empty str or bytes).

required
ttl_seconds float

Positive finite lifetime in seconds before the pin expires.

5.0
bind_key str | None

Logical database bind key protected by this pin.

None
causal_token str | None

Optional adapter causal token (such as WAL LSN or GTID set).

None
clock Callable[[], float]

Wall-clock epoch provider in seconds.

time

Returns:

Type Description
str

Cookie-safe ASCII token verifiable with :func:verify_primary_pin.

verify_primary_pin

verify_primary_pin(token, secret, *, bind_key=None, clock=time.time)

Verify an HMAC-signed primary pin cookie value and check expiration and bind key.

Parameters:

Name Type Description Default
token Any

Raw cookie value supplied by the client; a missing or non-string value is invalid.

required
secret str | bytes

Shared HMAC secret key (non-empty str or bytes).

required
bind_key str | None

Logical database bind key expected for this check.

None
clock Callable[[], float]

Wall-clock epoch provider in seconds.

time

Returns:

Type Description
tuple[bool, str | None]

Tuple (is_valid, causal_token); (False, None) when invalid or expired.

Replica Specifications, Circuit Breakers, and Selectors

ReplicaSpec

Weighted replica configuration with an optional declared staleness bound.

ReplicaHealthBreaker

Passive circuit breaker reserving at most one expired-open probe.

RoundRobinSelector

Smooth weighted round-robin using storage proportional to replica count.

RandomSelector

Weighted random ordering without replacement.