
Overview
In a number of scenarios, it is important to ensure that certain requests are routed to a specific Machine. This frequently is expressed in the form of wanting an entire user’s session to be processed by the same Machine. There are two approaches to addressing this with Fly.io:- fly-force-instance-id - Client-side request header
- fly-replay - Server-side response header
Fly-Force-Instance-Id
This approach requires you to have control over the client, typically a browser, but allows for immediate routing without an additional hop. The example below uses Rails’ Hotwire Turbo with Stimulus to send the required header. For this to work, the client needs some way of knowing what Machine to route requests to. This can be accomplished by adding attributes to the<body> tag in HTML responses. With Rails, those tags would be found in
app/views/layouts/application.html.erb.
An example <body> tag:
app/javascript/controllers/sticky-session.js:
fly-force-instance-id header into requests.
Fly-Replay
This approach is implemented entirely on the server. Your application examines each request, determines which Machine should handle it, and returns afly-replay response header to route the request accordingly. Initial requests will require an additional “hop” to route, and requests are limited to payloads of 1 megabyte.
The example below creates Express Middleware that routes requests based on a session cookie:
Optimizing with Replay Caching
For production workloads, having your application replay every request can create unnecessary load and latency. You can configure Fly Proxy to cache replay decisions, so only the first request in a session needs to consult your application. Add replay cache rules to yourfly.toml:
- The first request with a given
session_idhits your app - Your app returns a
fly-replayresponse - Fly Proxy caches this decision for that specific
session_idvalue - For the next 5 minutes, requests with the same
session_idare automatically routed without consulting your app
Authorization header.
For complete details on replay caching configuration, see Session-based Replay Caching.
Related reading
- Dynamic Request Routing with
fly‑replayExplains howfly‑replaylets you route requests to a specific machine or region—core technique for sticky sessions. - Load Balancing Details how the Fly Proxy routes traffic among Machines, which underpins how session‑affinity decisions get made.
- Networking A broad overview of how Fly handles public/private networking, Anycast IPs, WireGuard mesh, domain routing, and more.