Tooling & production/Multi-Node & Scale
Multi-Node & Scale
Running multiple Fletch replicas with Postgres/NATS/Redis PubSub, Quiver workers, health probes, and Live state deploy plans.
On this page
- Moving From One Node to Many
- Shared Postgres & Read Replicas (nock/postgres)
- Shared Sessions, Cache, and Storage
- Distributed Jobs (quiver/postgres, quiver/sqs)
- Distributed PubSub
- Live Components Across Replicas
- Sticky Sessions & Transport Fallback
- Broadcasting Across Replicas
- Deploy Compatibility Plans (fletch state plan)
- Health Probes & Zero-Downtime Rollouts
- Graceful Draining (fletch.Run)
- Migrations Across Replicas
- Observability (obs)
A single-node Fletch app can run on SQLite, local disk storage, and in-memory PubSub and jobs. Moving to multiple stateless replicas behind a load balancer requires replacing every node-local store with a shared backend, configuring health probes and graceful shutdown, and checking Live component state compatibility across deploys.
Moving From One Node to Many
Each Fletch subsystem sits behind a small interface, so switching from single-node defaults to shared infrastructure happens in bootstrap/app.go without rewriting module handlers.
| Subsystem | Single-Node Default | Multi-Node Backends |
|---|---|---|
| Database | nock/sqlite |
nock/postgres (plus WithReplica + nock.OnPrimary(ctx)) |
| Sessions | SQLite / local store | auth.DBSessions(db, auth.WithPostgres()) or auth/redis |
| Cache | In-memory | cache/redis or cache/postgres |
| File storage | Local disk | storage/s3 |
| Background jobs | quiver/sqlite / memory |
quiver/postgres or quiver/sqs |
| PubSub | In-memory | pubsub/postgres, pubsub/nats, pubsub/redis, or pubsub/sns |
Shared Postgres & Read Replicas (nock/postgres)
Use github.com/fletchhq/fletch/nock/postgres as the primary database across all replicas. When read traffic grows, attach one or more read replicas with WithReplica.
Read-heavy queries route to replicas automatically. For read-after-write flows where replication lag would return stale data (such as redirecting right after inserting a record), pin the query context to the primary with nock.OnPrimary(ctx):
ctx = nock.OnPrimary(ctx)
row, err := loadOrder(ctx, db, orderID)
Shared Sessions, Cache, and Storage
- Sessions: pass
auth.DBSessions(db, auth.WithPostgres())to keep sessions in Postgres with no extra service, or switch togithub.com/fletchhq/fletch/auth/rediswhen you want lower session-read latency under high request volume. - Cache: choose
github.com/fletchhq/fletch/cache/postgresif you want to stay on Postgres alone, orgithub.com/fletchhq/fletch/cache/redisfor higher throughput and TTL-heavy workloads. - File storage: configure
github.com/fletchhq/fletch/storage/s3so uploads written by replica A are readable from replica B and survive container restarts.
Distributed Jobs (quiver/postgres, quiver/sqs)
Move background jobs to github.com/fletchhq/fletch/quiver/postgres or github.com/fletchhq/fletch/quiver/sqs. You can run worker loops inside your web replicas or split them out into dedicated ./app work processes sharing the same queue backend.
As a safety check, Fletch refuses to start with the in-memory fallback queue when Postgres is configured outside dev mode. If you intentionally want an ephemeral in-memory queue in a staging or test deployment, opt in explicitly with WithAllowMemoryQueue().
Distributed PubSub
Select a PubSub backend that matches your operational footprint:
pubsub/postgres: runs over your existing Postgres database with a backing table andLISTEN/NOTIFYcatch-up, supporting broadcast, consumer groups, and transactional publishing.pubsub/nats: uses NATS JetStream for high-throughput fan-out, durable queue groups, and native wildcard subjects.pubsub/redis: uses Redis Pub/Sub for live broadcast and Redis Streams for durable consumer groups.pubsub/sns: publishes to Amazon SNS with SNS-to-SQS fan-out or webhook delivery for AWS-native deployments.
Live Components Across Replicas
Sticky Sessions & Transport Fallback
Configure sticky sessions (cookie or client-IP affinity) on your load balancer for Live WebSocket routes. Sticky routing keeps the initial page render and subsequent WebSocket handshake on the same replica whenever possible.
If a corporate firewall, proxy, or edge layer blocks WebSocket upgrades, Fletch’s Live client supports an SSE+POST transport fallback so interactive components continue working over standard HTTP.
Broadcasting Across Replicas
A Live component’s in-memory state lives on the replica holding its socket. When a mutation runs on replica A (from an HTTP handler, a Quiver job, or another Live component), publish an event through pubsub. Every replica subscribed to that topic receives the message and updates its connected Live bindings.
Deploy Compatibility Plans (fletch state plan)
Rolling deployments briefly run old and new replicas side by side, and reconnecting Live clients send state snapshots created by the previous binary. Run fletch state plan in CI to inspect how changes to your Live components affect connected browsers:
fletch state plan [dir] [--baseline] [--fail-on-remount] [--write-manifest]
Each modified Live component receives one of three classifications:
| Classification | What Changed | Client Behavior on Reconnect |
|---|---|---|
resume |
State struct and template signature remain compatible | Client reconnects and keeps its current state |
rerender |
Markup or rendering logic changed while state shape stayed compatible | Server re-renders with existing state and patches the DOM |
remount |
State struct changed in an incompatible way (removed/retyped fields) | Old state is discarded and the component mounts fresh |
Use --baseline to compare your working tree against the manifest from the currently deployed release. Pass --fail-on-remount in CI to block deploys that would unexpectedly drop user form state, and pass --write-manifest during release builds to save the new baseline artifact.
Health Probes & Zero-Downtime Rollouts
Fletch registers two HTTP probe endpoints by default:
/healthz: liveness probe. Returns200 OKwhile the HTTP server process is alive and responding./readyz: readiness probe. Checks the primary database connection and every registered custom pinger, returning non-200 when a required dependency is unreachable or the process is draining.
Register additional readiness dependencies (Redis, NATS, external gateways) using fletch.WithPinger(name, p):
app := fletch.New(
fletch.WithPinger("redis", redisClient),
)
To rename the endpoints for an existing ingress configuration, pass fletch.WithHealthPaths(live, ready). To disable the built-in probe routes and mount your own handlers, pass fletch.WithoutHealthChecks().
Point your orchestrator’s liveness check at /healthz and your load balancer target-group or Kubernetes readiness probe at /readyz. Never check downstream databases in a liveness probe, or a transient DB blip will trigger a restart loop across every replica.
Graceful Draining (fletch.Run)
fletch.Run handles SIGTERM and SIGINT so a rolling deploy lets in-flight requests finish and moves Live clients to a healthy replica. Requests still running when the shutdown grace period ends are cut off, so size the grace period to your slowest normal request.
On receiving a termination signal, fletch.Run does the following:
- Flips
/readyzto unhealthy so the load balancer stops sending new traffic to the terminating replica. - Waits for the deregister delay while continuing to serve requests that were already routed by the load balancer during target-group propagation.
- Stops accepting new connections and, as the HTTP shutdown begins, sends a WebSocket
1001(Going Away) close frame to every active Live connection so browsers reconnect right away to a healthy replica. - Waits up to the shutdown grace period for in-flight HTTP requests and then active Quiver workers to finish, runs
OnShutdownhooks, then closes database pools and registered providers.
| Option | Environment Variable | Default | Purpose |
|---|---|---|---|
WithDeregisterDelay |
$FLETCH_DEREGISTER_DELAY |
0s |
Wait time after failing /readyz before closing listeners |
WithShutdownGrace |
$FLETCH_SHUTDOWN_GRACE |
10s |
Maximum wait for in-flight HTTP requests, Live closes, and Quiver workers |
On AWS ECS or Kubernetes, set $FLETCH_DEREGISTER_DELAY to match your target group or Service propagation window (commonly 5s to 15s) and ensure the container stop timeout exceeds the sum of both values.
Migrations Across Replicas
Running automatic migrations inside web containers creates unnecessary startup contention and risks partial schema changes during failed rollouts. In config/environments/production.yaml, disable automatic migrations on boot:
database:
auto_migrate: false
Run ./app migrate once per deployment as a release command, Kubernetes Job, or ECS one-off task before shifting traffic to the new image.
nock/migrate acquires a database advisory or transaction lock before applying SQL files and verifies migration checksums. Even if two deployment pipelines invoke ./app migrate simultaneously, the second process waits on the lock and exits cleanly once the first completes.
Observability (obs)
github.com/fletchhq/fletch/obs adds distributed tracing and Prometheus metrics at the application boundary while keeping OpenTelemetry dependencies out of core Fletch modules (crest, router, live, nock, quiver, pubsub).
Initialize telemetry with obs.New using the functional options you need:
telemetry := obs.New(
obs.WithTracerProvider(tp),
obs.WithMetricsPath("/metrics"),
obs.WithXRay(),
)
obs.WithTracerProvider: attaches your configured OpenTelemetry tracer provider for outbound spans and request tracing.obs.WithMetricsPath: exposes Prometheus metrics at the given path (for example/metrics) for scraping across replicas.obs.WithXRay: enables AWS X-Ray trace header propagation alongside standard W3C Trace Context headers so traces stay intact across ALBs, API Gateway, ECS tasks, and SQS/SNS hops.