Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › HAProxy

How to Handle Session Persistence Across Servers in HAProxy

By Freedom251 Team · · 10 min read

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

HAProxy session persistence (often called sticky sessions) keeps a client’s requests on the same backend server after the initial load-balancing decision. For HTTP applications, an HAProxy-inserted cookie is usually the most precise option. For HTTP or raw TCP traffic, a source-IP stick table can provide affinity, but users sharing one public address may be grouped together. If several HAProxy nodes can receive the same client, replicate stick-table data with a peers section. Persistence only preserves routing information; it does not copy application memory, so sessions that must survive a server change need shared state or a stateless application design.

What session persistence changes in a load-balanced system

Without persistence, HAProxy selects a backend according to the configured balancing algorithm for each request. With persistence, the first selection creates an identity-to-server association, and later requests use that association whenever the selected server remains available.

HAProxy’s official tutorial describes two principal mechanisms:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

As an Amazon Associate I earn from qualifying purchases.

  • HTTP cookie persistence: HAProxy inserts a cookie identifying the selected server. The browser sends that cookie on subsequent HTTP requests.
  • Source-IP stickiness: HAProxy stores the client’s source address in a stick table and associates it with the selected server. This works in HTTP and TCP modes.

Persistence is useful when an application keeps login state, shopping-cart data, upload progress or other temporary information in one backend process. It is not a substitute for shared session storage. If the backend that owns a session disappears, HAProxy can route the next request elsewhere, but the replacement server cannot see memory that existed only on the failed process.

Choose the persistence method that matches your traffic

Method HAProxy mode Client identity Important limitation
Inserted HTTP cookie mode http Browser session cookie containing a server value Requires HTTP-aware processing; clients that do not return the cookie do not retain cookie-based affinity
Source-IP stick table HTTP or TCP Source IP address Many users behind one NAT gateway, reverse proxy or other shared address can be assigned to the same backend

Use the cookie method when you control HTTP traffic and need per-browser precision. Choose source-IP persistence for TCP services or protocols where inserting an HTTP cookie is impossible. If users arrive through a proxy, verify which address HAProxy actually sees before relying on source-IP affinity; a shared address reduces its precision.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Configure an HAProxy persistence cookie

The following backend uses round-robin for the initial choice and then inserts a cookie named SERVER_USED. Each server line supplies a distinct cookie value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
backend app
    mode http
    balance roundrobin
    cookie SERVER_USED insert indirect nocache
    server app1 192.168.0.10:80 check cookie app1
    server app2 192.168.0.11:80 check cookie app2

What each directive does

  • mode http enables HTTP processing, which is required for HAProxy to insert and read an HTTP persistence cookie.
  • balance roundrobin decides where a client goes when no usable persistence information exists. It also provides the initial distribution in this example.
  • cookie SERVER_USED sets the cookie name that identifies the backend server.
  • insert tells HAProxy to add the cookie to the response sent to the client.
  • indirect keeps the persistence cookie from being sent to the backend application as an ordinary client cookie.
  • nocache adds the cache-control behavior HAProxy uses with this persistence-cookie pattern so an intermediary does not incorrectly reuse a response containing a server-selection cookie.
  • cookie app1 and cookie app2 assign stable, distinct values to the two servers.
  • check enables health checks, allowing HAProxy to avoid a server that is not available.

After the first response, inspect the browser’s cookies and look for SERVER_USED=app1 or SERVER_USED=app2. A later request that includes that value is routed to the matching healthy server. If no cookie is present, if the value does not match a configured server, or if the associated server is unavailable, HAProxy falls back to its normal server-selection and failure-handling rules.

Use dynamic cookie values when several HAProxy nodes must agree

HAProxy can derive a cookie value from the server’s IP address, port and a shared secret instead of requiring a manually assigned value on each server line.

backend app
    mode http
    cookie SERVER_USED insert indirect nocache dynamic
    dynamic-cookie-key a-long-shared-secret
    server app1 192.168.0.10:80 check
    server app2 192.168.0.11:80 check

Every HAProxy node that may receive the same client must use the same dynamic-cookie secret and a compatible identity for each backend server. Otherwise, one node may not be able to interpret the cookie created by another. If a server line includes an explicit cookie argument, that explicit value overrides the dynamically derived value.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Keep the secret consistent during configuration distribution and rolling changes. Changing it changes the values HAProxy expects, so existing client cookies may no longer map to a server and clients can be redistributed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure source-IP persistence with a stick table

Source-IP persistence is suitable when the traffic is not HTTP or when you need a transport-level method. This example uses TCP mode and retains entries for 30 minutes.

backend app
    mode tcp
    stick-table type ip size 1m expire 30m
    stick on src
    server app1 192.168.0.10:80 check
    server app2 192.168.0.11:80 check

How the source-IP example works

  • mode tcp makes the configuration usable for TCP traffic without HTTP inspection.
  • stick-table type ip stores IPv4 or IPv6 client addresses as the key.
  • size 1m reserves capacity for the configured stick-table entries.
  • expire 30m removes an entry after 30 minutes without the activity that refreshes it. The 30-minute value is the expiration shown in HAProxy’s official session-persistence example, not a universal requirement.
  • stick on src tells HAProxy to use the connection’s source address as the key.

The source address must represent the client population you want to separate. If thousands of browsers reach HAProxy through one reverse proxy or NAT gateway, they all present the same key and can be pinned to one backend. That can create uneven load and does not provide browser-level isolation. In such a topology, HTTP cookie persistence or application-managed shared state is generally more precise.

Keep affinity when clients can reach multiple HAProxy instances

A cookie can be interpreted independently by each HAProxy node when the nodes share the same cookie configuration and backend identity. Source-IP stickiness is different: the association lives in each node’s in-memory stick table. If a floating address, DNS response or upstream load balancer sends the next connection to another HAProxy instance, that instance needs the same stick-table entry.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Use a peers section to replicate stick-table data:

peers mycluster
    peer lb1 192.168.1.10:10000
    peer lb2 192.168.1.11:10000

backend app
    stick-table type ip size 1m expire 30m peers mycluster
    stick on src
    server app1 192.168.0.10:80 check id 1
    server app2 192.168.0.11:80 check id 2

Configure peer identity and connectivity

  1. Define every HAProxy node in the same peers section, giving each node a unique peer name and its reachable peer address.
  2. Reference that section on the stick table with peers mycluster.
  3. Ensure the peer addresses and port are reachable through firewalls and network policy.
  4. Use the same table definition on all nodes, including key type and expiration, so replicated entries have equivalent meaning.
  5. Assign explicit, matching server IDs when the same backend identity must be recognized consistently. In the example, app1 is id 1 and app2 is id 2.

HAProxy documents peer replication as especially useful in active-standby designs. It also supports continuity across a reload: the old process can connect to the new process and transfer stick-table entries. Without that handoff, entries held only in memory are lost during the reload.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Account for synchronization overhead

Peer replication is not free. Every update that must be sent to another node consumes synchronization traffic, and a large table consumes memory on each participating process. High connection rates, short expiration periods and frequent updates can increase the amount of data exchanged. Size the table for the active client population and monitor memory and peer-link health rather than choosing an arbitrarily large value.

Enterprise Global Profiling Engine deployments

For HAProxy Enterprise Global Profiling Engine deployments, the documentation instructs operators to reference a shared sessions table in the peers section and to assign explicit server IDs so that all load balancers map the same server identity. The HAProxy Enterprise documentation build date identified for that guidance is 2025-11-21. Apply the exact table and server-ID requirements for the Enterprise version in use; do not assume a configuration written for a different release has identical directives.

What happens when the preferred backend fails

Persistence does not make a failed server available. When a request carries a persistence cookie for a server that is down, HAProxy normally redispatches the request to another available server. The replacement server may not have the user’s in-memory login or workflow state.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

option persist changes that behavior by making HAProxy try the unavailable server first. This is a specialized choice for environments where a flapping server may recover and where preserving the original association is more important than immediately selecting a healthy alternative. It should not be enabled casually: sending traffic toward an unavailable server can delay recovery and does not restore application state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Design the application for replacement

If a user must remain logged in or retain a cart after backend replacement, keep the state outside the individual backend process. Suitable patterns include:

  • A shared database for durable session records.
  • A shared cache or session service reachable by every backend.
  • Stateless, signed client tokens when the application’s security and revocation model permits them.

HAProxy’s tutorial identifies stateless design with off-server state as preferable where the application allows it. Sticky routing can reduce cross-server lookups, but it should be treated as an optimization, not the only copy of important state.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Cookie persistence versus source-IP persistence

Decision axis Cookie persistence Source-IP stickiness
Protocol requirement HTTP mode HTTP or TCP mode
Granularity Individual browser session when the cookie is returned One source address, which may represent many users
Configuration state Cookie value identifies the backend server Stick table stores the source address and selected server
Multi-node concern Share cookie secret and compatible server identity when using dynamic values Replicate the stick table with peers when a client can land on different nodes
Failure result Normal behavior is redispatch when the cookie’s server is unavailable Normal behavior is redispatch when the associated server is unavailable

Neither method transfers application memory. The deciding question is whether the client identity can be represented accurately at the layer HAProxy can observe.

Validate a new persistence configuration

  1. Validate the configuration before reload. Use the configuration-check procedure appropriate to your HAProxy installation and reject the change if parsing reports an error.
  2. Test first selection. Send a request without a persistence cookie, then record which backend answered and inspect the response for the configured cookie name.
  3. Test repeat selection. Send several requests with the returned cookie and verify that they continue to reach the same healthy server.
  4. Test cookie removal. Delete the cookie or use a clean client session and confirm that HAProxy can make a new initial selection.
  5. Test health failure. Mark the associated backend unavailable in a controlled environment and verify that traffic redispatches to an available server.
  6. Test node changes. With multiple HAProxy instances, send successive requests through different nodes. Confirm that dynamic-cookie settings are identical and that source-IP entries appear on the peer node.
  7. Test reload continuity. Perform a controlled reload and check whether existing stick-table associations survive through the old-to-new process handoff.
  8. Test application recovery. End the original backend session and confirm that shared state or stateless credentials let the replacement backend complete the request.

Troubleshoot common symptoms

The browser keeps moving between servers

  • Confirm the backend is in mode http and that the cookie directive is on the intended backend.
  • Check that the response actually contains the configured cookie and that the client accepts and returns it.
  • Verify that each server has a distinct explicit cookie value, or that all nodes share the same dynamic-cookie-key and compatible server identity.
  • Check whether health checks are marking the preferred server unavailable; normal failure handling can legitimately select another server.

Several users are concentrated on one backend

This is expected when source-IP persistence sees a shared NAT gateway, reverse proxy or other common address. Use HTTP cookie persistence for browser-level identity, or change the application design so that requests can safely reach any backend.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Stickiness disappears after a reload

Entries kept only in memory are lost when the old process does not transfer them to the new process. Associate the stick table with a peers section and verify that the old and new processes can establish the reload handoff.

Affinity works on one HAProxy node but not another

For source-IP tables, inspect peer connectivity and confirm that the table references the same peers section on every node. For dynamic cookies, compare the secret, backend addresses, ports and server identities. Explicit server cookie values must also match wherever they are configured.

The user reaches the replacement server but is logged out

This is an application-state problem, not a routing failure. Move session data to a shared database or cache, or adopt a stateless session design. Keeping the same HAProxy route cannot recreate memory that existed only in the failed backend process.

Operational checklist

  • Choose cookie persistence for precise HTTP client identity; choose source-IP persistence when TCP support or protocol neutrality is required.
  • Give every backend server a stable identity, especially when dynamic cookies or replicated tables are used.
  • For multiple HAProxy nodes, replicate source-IP tables with peers and align table definitions.
  • Use explicit server IDs when all load balancers must map the same backend identity.
  • Size stick tables and peer links for the expected update rate and client population.
  • Expect redispatch when a persisted server is unavailable unless a deliberate option persist policy says otherwise.
  • Store important session state off-server so a backend failure does not become a user-visible logout or data loss.
  • Test first selection, repeat requests, failure, reload and cross-node routing before production rollout.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

HAProxyHigh Availabilityload balancingsession persistencestick tablessticky sessions

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.