{"id":1986,"date":"2025-11-17T20:47:37","date_gmt":"2025-11-17T17:47:37","guid":{"rendered":"https:\/\/www.dchost.com\/blog\/canary-deploys-on-a-vps-the-friendly-guide-to-nginx-weighted-routing-health-checks-and-safe-rollbacks\/"},"modified":"2026-11-04T08:35:40","modified_gmt":"2026-11-04T05:35:40","slug":"nginx-canary-deployment-vps","status":"publish","type":"post","link":"https:\/\/www.dchost.com\/blog\/en\/nginx-canary-deployment-vps\/","title":{"rendered":"Nginx Canary Deployment on a VPS"},"content":{"rendered":"<div class=\"dchost-blog-content-wrapper\"><div id=\"toc_container\" role=\"navigation\" aria-label=\"Table of Contents\" data-nosnippet class=\"toc_transparent no_bullets toc_numbered toc_title_center\"><p class=\"toc_title\">\u0130\u00e7indekiler<\/p><ul class=\"toc_list\"><li><a href=\"#Nginx_Canary_Deployment_on_a_VPS\"><span class=\"toc_number toc_depth_1\">1.<\/span> Nginx Canary Deployment on a VPS<\/a><\/li><li><a href=\"#What_a_Canary_Deploy_Looks_Like_on_a_Single_VPS\"><span class=\"toc_number toc_depth_1\">2.<\/span> What a Canary Deploy Looks Like on a Single VPS<\/a><\/li><li><a href=\"#Prepare_Two_Application_Versions\"><span class=\"toc_number toc_depth_1\">3.<\/span> Prepare Two Application Versions<\/a><ul><li><a href=\"#Two_app_processes_two_ports\"><span class=\"toc_number toc_depth_2\">3.1.<\/span> Two app processes, two ports<\/a><\/li><li><a href=\"#Nginx_Routes_Requests\"><span class=\"toc_number toc_depth_2\">3.2.<\/span> Nginx Routes Requests<\/a><\/li><li><a href=\"#Health_checks\"><span class=\"toc_number toc_depth_2\">3.3.<\/span> Health checks<\/a><\/li><li><a href=\"#Traffic_rollbacks\"><span class=\"toc_number toc_depth_2\">3.4.<\/span> Traffic rollbacks<\/a><\/li><\/ul><\/li><li><a href=\"#Configure_Nginx_Weighted_Routing\"><span class=\"toc_number toc_depth_1\">4.<\/span> Configure Nginx Weighted Routing<\/a><\/li><li><a href=\"#Identify_Canary_Attempts_in_Logs\"><span class=\"toc_number toc_depth_1\">5.<\/span> Identify Canary Attempts in Logs<\/a><\/li><li><a href=\"#Passive_Failure_Accounting_and_Retries\"><span class=\"toc_number toc_depth_1\">6.<\/span> Passive Failure Accounting and Retries<\/a><\/li><li><a href=\"#An_External_Canary_Readiness_Checker\"><span class=\"toc_number toc_depth_1\">7.<\/span> An External Canary Readiness Checker<\/a><\/li><li><a href=\"#A_Shared_State_File_for_Routing_and_Rollback\"><span class=\"toc_number toc_depth_1\">8.<\/span> A Shared State File for Routing and Rollback<\/a><\/li><li><a href=\"#Compare_Canary_and_Stable_Observations\"><span class=\"toc_number toc_depth_1\">9.<\/span> Compare Canary and Stable Observations<\/a><\/li><li><a href=\"#A_Measured_Canary_Rollout\"><span class=\"toc_number toc_depth_1\">10.<\/span> A Measured Canary Rollout<\/a><\/li><li><a href=\"#Session_Cache_and_Database_Compatibility\"><span class=\"toc_number toc_depth_1\">11.<\/span> Session, Cache and Database Compatibility<\/a><\/li><li><a href=\"#Optional_Hash_Buckets_with_split_clients\"><span class=\"toc_number toc_depth_1\">12.<\/span> Optional Hash Buckets with split_clients<\/a><\/li><li><a href=\"#TLS_and_Graceful_Reload_Limitations\"><span class=\"toc_number toc_depth_1\">13.<\/span> TLS and Graceful Reload Limitations<\/a><\/li><li><a href=\"#Retry_and_Timeout_Tradeoffs\"><span class=\"toc_number toc_depth_1\">14.<\/span> Retry and Timeout Tradeoffs<\/a><\/li><li><a href=\"#Protect_Control_Scripts_and_Private_Endpoints\"><span class=\"toc_number toc_depth_1\">15.<\/span> Protect Control Scripts and Private Endpoints<\/a><\/li><li><a href=\"#Common_Canary_Configuration_Errors\"><span class=\"toc_number toc_depth_1\">16.<\/span> Common Canary Configuration Errors<\/a><\/li><li><a href=\"#A_Canary_Rollout_Checklist\"><span class=\"toc_number toc_depth_1\">17.<\/span> A Canary Rollout Checklist<\/a><\/li><li><a href=\"#Feature_Flags_and_Other_Canary_Changes\"><span class=\"toc_number toc_depth_1\">18.<\/span> Feature Flags and Other Canary Changes<\/a><\/li><li><a href=\"#Complete_the_Rollout_with_Verified_Evidence\"><span class=\"toc_number toc_depth_1\">19.<\/span> Complete the Rollout with Verified Evidence<\/a><\/li><li><a href=\"#Nginx_Reference_Documentation\"><span class=\"toc_number toc_depth_1\">20.<\/span> Nginx Reference Documentation<\/a><\/li><\/ul><\/div>\n<h2 id=\"section-1\"><span id=\"Nginx_Canary_Deployment_on_a_VPS\">Nginx Canary Deployment on a VPS<\/span><\/h2>\n<p>A canary deployment sends limited traffic to a new release while a stable release remains available. On a single <a href=\"https:\/\/www.dchost.com\/vps\">VPS<\/a>, both versions share CPU, memory, storage and the host failure domain. Check capacity for simultaneous processes before rollout. Canary observation complements staging and recovery preparation; it does not prove a release safe.<\/p>\n<p>This guide covers two app versions running side-by-side, <strong>Nginx weighted routing<\/strong> to send a small share of requests to the canary, <strong>health checks<\/strong> to help detect failures, and <strong>traffic rollbacks<\/strong> when needed. Routing changes do not undo database changes or other application side effects, so both versions must remain compatible during the rollout.<\/p>\n<h2 id=\"section-2\"><span id=\"What_a_Canary_Deploy_Looks_Like_on_a_Single_VPS\">What a Canary Deploy Looks Like on a Single VPS<\/span><\/h2>\n<p>Run stable v1 and canary v2 as separate, identifiable application processes. Start with v2 unavailable to general routing, test it directly, then increase its share while comparing errors, latency and important user operations against v1. Define minimum sample sizes and stop criteria beforehand. A traffic rollback does not undo completed writes, payments or queued jobs.<\/p>\n<p>Nginx receives public traffic and selects a backend. In the weighted pool, configured retry rules may permit another attempt on a different available peer. A forced single-peer canary route has no stable peer to retry. Keep both paths under one enable\/disable gate, and verify the actual backend rather than assuming a successful client response means canary succeeded.<\/p>\n<p>For example, a hypothetical rollout could send roughly 5% of requests to v2. A rise in canary 5xx responses would be a reason to pause or roll back traffic, investigate a possible cache-key incompatibility, and resume only after validating a fix.<\/p>\n<h2 id=\"section-3\"><span id=\"Prepare_Two_Application_Versions\">Prepare Two Application Versions<\/span><\/h2>\n<h3><span id=\"Two_app_processes_two_ports\">Two app processes, two ports<\/span><\/h3>\n<p>This example uses loopback HTTP on 127.0.0.1:5001 for v1 and 127.0.0.1:5002 for v2. Check that those ports and the local configuration probe port 18089 are available. Manage the processes through your own service\/container setup and keep backend ports private. The canary <code>\/healthz<\/code> must return exactly HTTP 200 and the body <code>ok version=v2<\/code> followed by one LF only when the chosen readiness contract is met.<\/p>\n<h3><span id=\"Nginx_Routes_Requests\">Nginx Routes Requests<\/span><\/h3>\n<p>Nginx will sit in front and route traffic with weighted round-robin. You can fine-tune weights to approximate percentages. The weights govern request selection, not sticky user assignment; short samples, retries, and unavailable peers can change the observed share.<\/p>\n<h3><span id=\"Health_checks\">Health checks<\/span><\/h3>\n<p>Open-source Nginx provides passive failure accounting in a multi-peer upstream through <code>max_fails<\/code> and <code>fail_timeout<\/code>. These parameters are ignored for a single-server group. Our separate curl checker tests the canary directly and attempts to close the shared gate after three consecutive failures. This external probe does not require NGINX Plus and is not comprehensive application monitoring.<\/p>\n<h3><span id=\"Traffic_rollbacks\">Traffic rollbacks<\/span><\/h3>\n<p>The helper below validates positive integer weights, serializes cooperating writers, replaces one state file atomically and attempts restoration after validation\/reload failure. That state file controls both the weighted peer and the forced-cookie route. The helper reports whether a new configuration generation was observed; it cannot guarantee instant traffic cutover or recover application side effects.<\/p>\n<h2 id=\"section-4\"><span id=\"Configure_Nginx_Weighted_Routing\">Configure Nginx Weighted Routing<\/span><\/h2>\n<p>Merge the following fragment once into the existing <code>http<\/code> context. Create the state file shown later before validating this configuration; do not duplicate upstream or log_format names. Adapt the server to your existing HTTPS configuration. Applications must supply a trusted <code>X-Release: v1<\/code> or <code>X-Release: v2<\/code> response header. The loopback-only generation endpoint reports Nginx configuration state, not application readiness.<\/p>\n<pre class=\"language-nginx line-numbers\"><code class=\"language-nginx\"># Merge once into the existing http context; do not duplicate upstream names.\nupstream app_stable { server 127.0.0.1:5001; }\nupstream app_canary { server 127.0.0.1:5002; }\ninclude \/etc\/nginx\/canary-state.conf;\n\nmap &quot;$canary_enabled:$cookie_canary&quot; $backend_upstream {\n    default app_pool;\n    &quot;1:1&quot;   app_canary;\n}\n\nlog_format canary_json escape=json\n    &#039;{&quot;time&quot;:&quot;$time_iso8601&quot;,&quot;status&quot;:$status,&#039;\n    &#039;&quot;route&quot;:&quot;$backend_upstream&quot;,&quot;upstream&quot;:&quot;$upstream_addr&quot;,&#039;\n    &#039;&quot;upstream_status&quot;:&quot;$upstream_status&quot;,&quot;release&quot;:&quot;$upstream_http_x_release&quot;,&#039;\n    &#039;&quot;request_time&quot;:$request_time,&quot;upstream_time&quot;:&quot;$upstream_response_time&quot;}&#039;;\n\nserver {\n    listen 80;\n    server_name example.com;\n    access_log \/var\/log\/nginx\/canary.json canary_json;\n    location \/ {\n        proxy_set_header Host $host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n        proxy_http_version 1.1;\n        proxy_set_header Connection &quot;&quot;;\n        proxy_connect_timeout 2s;\n        proxy_send_timeout 30s;\n        proxy_read_timeout 30s;\n        proxy_next_upstream error timeout http_502 http_503 http_504;\n        proxy_next_upstream_tries 2;\n        proxy_pass http:\/\/$backend_upstream;\n    }\n}\n\n# Local configuration-generation probe, not application readiness.\nserver {\n    listen 127.0.0.1:18089;\n    server_name localhost;\n    access_log off;\n    location = \/__canary_generation { return 200 &quot;$canary_generation\\n&quot;; }\n    location \/ { return 404; }\n}\n<\/code><\/pre>\n<p>The initial state keeps canary disabled. After enabling, its target weighted share is <strong>canary \/ (stable + canary)<\/strong>: stable 100 with canary 1 is about 0.99%, 5 about 4.76%, 20 about 16.67%, 50 about 33.33%, and 100 about 50%. Cookie overrides, unavailable peers, retries and short samples change observed shares. Weight 0 is invalid as an upstream weight; use the helper\u2019s disable action, which writes <code>down<\/code> and closes the common gate.<\/p>\n<p>For a hash-bucket alternative, <a href=\"http:\/\/nginx.org\/en\/docs\/http\/ngx_http_split_clients_module.html\" rel=\"nofollow noopener\" target=\"_blank\">split_clients<\/a> maps a key into a configured fraction of the hash space. The same key and unchanged split remain deterministic, but shared\/changing IPs and changing user agents do not identify stable individual users. Unequal activity also means bucket fractions differ from request-volume fractions. The optional example later replaces the routing map while retaining the shared disable gate.<\/p>\n<p>The default example recognizes an explicitly sent <code>Cookie: canary=1<\/code> only while canary is enabled. It does not create that cookie or restrict access: any client can send it. Use separate authentication for team-only testing. Enabling this gate also opens the selected weighted share to ordinary traffic; direct backend or protected staging tests should come first. Browser cookie scope, HTTPS\/Secure, SameSite and applicable HttpOnly settings belong to the application\u2019s test flow.<\/p>\n<h2 id=\"section-5\"><span id=\"Identify_Canary_Attempts_in_Logs\">Identify Canary Attempts in Logs<\/span><\/h2>\n<p>The JSON format records the selected pool separately from actual upstream attempts. <code>release<\/code> comes from the final upstream response header; it is neither a complete retry history nor proof that an unauthenticated header is trustworthy. The following illustrative records show a direct canary success and a canary failure followed by a stable success:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">{&quot;time&quot;:&quot;2026-11-04T12:00:00+03:00&quot;,&quot;status&quot;:200,&quot;route&quot;:&quot;app_pool&quot;,&quot;upstream&quot;:&quot;127.0.0.1:5002&quot;,&quot;upstream_status&quot;:&quot;200&quot;,&quot;release&quot;:&quot;v2&quot;,&quot;request_time&quot;:0.120,&quot;upstream_time&quot;:&quot;0.115&quot;}\n{&quot;time&quot;:&quot;2026-11-04T12:00:01+03:00&quot;,&quot;status&quot;:200,&quot;route&quot;:&quot;app_pool&quot;,&quot;upstream&quot;:&quot;127.0.0.1:5002, 127.0.0.1:5001&quot;,&quot;upstream_status&quot;:&quot;503, 200&quot;,&quot;release&quot;:&quot;v1&quot;,&quot;request_time&quot;:0.025,&quot;upstream_time&quot;:&quot;0.010, 0.015&quot;}\n<\/code><\/pre>\n<p>Choose one bounded observation window before counting. This jq example assumes every timestamp and both boundaries use the same ISO 8601 format and UTC offset, as in this single Nginx log. Replace the example boundaries with your real window; normalize timestamps first if aggregating mixed offsets. Run analysis from a private directory with permission to read the log.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">set -euo pipefail\numask 077\njq -c --arg start_time &#039;2026-11-04T12:00:00+03:00&#039; \\\n      --arg finish_time   &#039;2026-11-04T12:10:00+03:00&#039; \\\n      &#039;select(.time &gt;= $start_time and .time &lt; $finish_time)&#039; \\\n      \/var\/log\/nginx\/canary.json &gt; .\/canary-window.jsonl\n<\/code><\/pre>\n<p>Verify the window contains actual canary attempts and enough observations for the rollout decision. Empty results can mean no canary traffic, the wrong window or missing logs; they are not a clean bill of health. Keep the same interval for stable and canary comparisons. Error logs may contain additional details and require their own access and retention controls.<\/p>\n<h2 id=\"section-6\"><span id=\"Passive_Failure_Accounting_and_Retries\">Passive Failure Accounting and Retries<\/span><\/h2>\n<p>In the weighted pool, the two retry directives below are already present in the main example. They illustrate the existing settings; do not add a second location block. Failure accounting depends on the configured conditions, so HTTP 500 or business-logic errors are not automatically covered by the listed HTTP 502\/503\/504 conditions.<\/p>\n<pre class=\"language-nginx line-numbers\"><code class=\"language-nginx\"># Already inside the main location \/ block; do not duplicate it.\nproxy_next_upstream error timeout http_502 http_503 http_504;\nproxy_next_upstream_tries 2;\n<\/code><\/pre>\n<p>These rules allow a retry on another available peer for the listed failures, in either direction\u2014not only canary to stable. Retries cannot recover a response already sent to the client, and non-idempotent requests already sent upstream are normally not retried. Continue monitoring errors and latency rather than assuming retries hide every failure.<\/p>\n<p>The <a href=\"http:\/\/nginx.org\/en\/docs\/http\/ngx_http_upstream_module.html\" rel=\"nofollow noopener\" target=\"_blank\">upstream module documentation<\/a> defines the single-server exception: max_fails\/fail_timeout do not mark the only peer unavailable. Our fixed app_canary route therefore exposes failures directly until the common gate is closed. Two total attempts means at most one retry; choose timeouts and failure thresholds for your workload rather than treating the example values as universal safe limits.<\/p>\n<h2 id=\"section-7\"><span id=\"An_External_Canary_Readiness_Checker\">An External Canary Readiness Checker<\/span><\/h2>\n<p>Save this guard as <code>\/usr\/local\/bin\/canary-healthcheck.sh<\/code> after preparing the helper below. It uses curl without environment proxies or redirect following, requires exactly HTTP 200 plus <code>ok version=v2<\/code> and one LF, and returns as soon as any attempt is healthy. Three consecutive failures within a run trigger disable; a helper failure propagates to systemd.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">#!\/usr\/bin\/env bash\nset -euo pipefail\numask 077\nbody=$(mktemp)\ntrap &#039;rm -f -- &quot;$body&quot;&#039; EXIT\nfor attempt in 1 2 3; do\n    if code=$(curl --noproxy &#039;*&#039; -sS --connect-timeout 1 --max-time 2 \\\n        -H &#039;Host: example.com&#039; -o &quot;$body&quot; -w &#039;%{http_code}&#039; \\\n        &#039;http:\/\/127.0.0.1:5002\/healthz&#039;) &amp;&amp;\n       [[ &quot;$code&quot; == 200 ]] &amp;&amp; cmp -s &quot;$body&quot; &lt;(printf &#039;ok version=v2\\n&#039;); then\n        exit 0\n    fi\n    if (( attempt &lt; 3 )); then sleep 1; fi\ndone\necho &quot;Three failed readiness probes; attempting canary disable&quot; &gt;&amp;2\n\/usr\/local\/bin\/canary-weight.sh disable\n<\/code><\/pre>\n<p>Save the service and timer below as two separate files at the indicated paths. The timer is relative to completion of the previous service run:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\"># Save as \/etc\/systemd\/system\/canary-healthcheck.service\n[Unit]\nDescription=Canary readiness check and traffic-disable attempt\n\n[Service]\nType=oneshot\nExecStart=\/usr\/local\/bin\/canary-healthcheck.sh\nTimeoutStartSec=180s\n\n# Save separately as \/etc\/systemd\/system\/canary-healthcheck.timer\n[Unit]\nDescription=Run canary readiness check after each completed run\n\n[Timer]\nOnBootSec=30s\nOnUnitInactiveSec=10s\nAccuracySec=1s\n\n[Install]\nWantedBy=timers.target\n<\/code><\/pre>\n<p>Install both scripts with root-controlled ownership and executable permissions, for example <code>chmod 0750 \/usr\/local\/bin\/canary-weight.sh \/usr\/local\/bin\/canary-healthcheck.sh<\/code>. After writing unit files, run <code>systemctl daemon-reload<\/code>, then <code>systemctl enable --now canary-healthcheck.timer<\/code>. Verify <code>systemctl status canary-healthcheck.timer<\/code> and <code>journalctl -u canary-healthcheck.service<\/code>. OnUnitInactiveSec waits about 10 seconds after a run finishes; AccuracySec, probe duration, lock waits and reloads add delay. This is not a fixed ten-second rollback guarantee. Test with the actual distribution\u2019s unit and Nginx service.<\/p>\n<h2 id=\"section-8\"><span id=\"A_Shared_State_File_for_Routing_and_Rollback\">A Shared State File for Routing and Rollback<\/span><\/h2>\n<p>Create <code>\/etc\/nginx\/canary-state.conf<\/code> with the following initial content before first loading the main configuration. Keep it a regular file in a directory writable only by authorized administrators. It contains the weighted upstream plus both maps, so peer selection and the forced route use one state transition.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\"># generation: initial\nupstream app_pool {\n    zone app_pool 64k;\n    keepalive 16;\n    server 127.0.0.1:5001 weight=100 max_fails=3 fail_timeout=10s;\n    server 127.0.0.1:5002 down;\n}\nmap $host $canary_enabled { default 0; }\nmap $host $canary_generation { default &quot;initial&quot;; }\n<\/code><\/pre>\n<p>After installing and testing the helper below, open a small share with its set action. Stable remains at weight 100; a canary weight of 5 is about 4.76% of eligible weighted selections. The same action enables the forced-cookie path. It is not an isolated team-only mode.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">\/usr\/local\/bin\/canary-weight.sh set 5\n<\/code><\/pre>\n<p>Disable switches the canary peer to down and closes the common gate, including the optional split route shown later. The helper already validates and reloads; do not add a second uncoordinated reload command:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">\/usr\/local\/bin\/canary-weight.sh disable\n<\/code><\/pre>\n<p>Save this helper as <code>\/usr\/local\/bin\/canary-weight.sh<\/code>. It requires Bash, curl, util-linux flock, GNU coreutils, sed and the guard\u2019s cmp utility (from diffutils on GNU systems). The example assumes a systemd-managed Nginx service, with authorized access to the state file, lock directory and service. It accepts only weights 1\u201310000 without leading zeros; <code>enable<\/code> selects weight 1 and <code>disable<\/code> writes down. All config writers and reloaders must honor this same lock.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">#!\/usr\/bin\/env bash\nset -euo pipefail\numask 077\nSTATE=&quot;\/etc\/nginx\/canary-state.conf&quot;\nLOCK=&quot;\/run\/lock\/dchost-canary.lock&quot;\nPROBE=&quot;http:\/\/127.0.0.1:18089\/__canary_generation&quot;\n\npositive_weight() {\n    [[ &quot;$1&quot; =~ ^[1-9][0-9]{0,4}$ ]] &amp;&amp; (( 10#$1 &lt;= 10000 ))\n}\nstable=100\ncase &quot;${1:-}&quot; in\n    set)\n        [[ $# == 2 ]] &amp;&amp; positive_weight &quot;$2&quot; || { echo &quot;Usage: canary-weight.sh set INTEGER_1_TO_10000&quot; &gt;&amp;2; exit 64; }\n        canary=$2 ;;\n    enable|disable)\n        [[ $# == 1 ]] || { echo &quot;Unexpected argument&quot; &gt;&amp;2; exit 64; }\n        if [[ &quot;$1&quot; == enable ]]; then canary=1; else canary=0; fi ;;\n    *) echo &quot;Usage: canary-weight.sh {set N|enable|disable}&quot; &gt;&amp;2; exit 64 ;;\nesac\n\nexec 9&gt;&quot;$LOCK&quot;\nflock -x -w 10 9 || { echo &quot;Another canary update holds the lock&quot; &gt;&amp;2; exit 1; }\n[[ -f &quot;$STATE&quot; &amp;&amp; ! -L &quot;$STATE&quot; ]] || { echo &quot;Expected a regular state file&quot; &gt;&amp;2; exit 1; }\nold_generation=$(sed -n &#039;s\/^# generation: \/\/p&#039; &quot;$STATE&quot;)\n[[ &quot;$old_generation&quot; =~ ^[A-Za-z0-9-]+$ ]] || { echo &quot;Invalid old generation&quot; &gt;&amp;2; exit 1; }\nbackup=&quot;&quot;; candidate=&quot;&quot;; probe_body=&quot;&quot;; dirty=0\n\nwait_generation() {\n    local wanted=$1 code attempt\n    for attempt in {1..10}; do\n        if code=$(curl --noproxy &#039;*&#039; -sS --connect-timeout 1 --max-time 1 \\\n            -H &#039;Connection: close&#039; -o &quot;$probe_body&quot; -w &#039;%{http_code}&#039; &quot;$PROBE&quot;) &amp;&amp;\n           [[ &quot;$code&quot; == 200 &amp;&amp; &quot;$(cat &quot;$probe_body&quot;)&quot; == &quot;$wanted&quot; ]]; then\n            return 0\n        fi\n        sleep 0.2\n    done\n    return 1\n}\n\ncleanup() {\n    local rc=$? restore\n    trap - EXIT HUP INT TERM\n    if (( dirty )); then\n        echo &quot;Restoring previous state from $backup&quot; &gt;&amp;2\n        if restore=$(mktemp &quot;${STATE}.restore.XXXXXX&quot;) &amp;&amp;\n           cp -p -- &quot;$backup&quot; &quot;$restore&quot; &amp;&amp; mv -fT -- &quot;$restore&quot; &quot;$STATE&quot; &amp;&amp;\n           nginx -t &amp;&amp; timeout 30 systemctl reload nginx &amp;&amp; wait_generation &quot;$old_generation&quot;; then\n            dirty=0\n        else\n            echo &quot;RESTORE NOT CONFIRMED. Preserve $backup and reconcile disk\/runtime manually.&quot; &gt;&amp;2\n            rc=2\n        fi\n    fi\n    [[ -z &quot;$candidate&quot; ]] || rm -f -- &quot;$candidate&quot;\n    [[ -z &quot;$probe_body&quot; ]] || rm -f -- &quot;$probe_body&quot;\n    if (( ! dirty )) &amp;&amp; [[ -n &quot;$backup&quot; ]]; then rm -f -- &quot;$backup&quot;; fi\n    exit &quot;$rc&quot;\n}\ntrap cleanup EXIT\ntrap &#039;exit 129&#039; HUP\ntrap &#039;exit 130&#039; INT\ntrap &#039;exit 143&#039; TERM\n\nbackup=$(mktemp &quot;${STATE}.backup.XXXXXX&quot;)\ncp -p -- &quot;$STATE&quot; &quot;$backup&quot;\ncandidate=$(mktemp &quot;${STATE}.new.XXXXXX&quot;)\nprobe_body=$(mktemp)\ngeneration=&quot;$(date +%s%N)-$$&quot;\nenabled=0\ncanary_line=&quot;server 127.0.0.1:5002 down;&quot;\nif (( canary &gt; 0 )); then\n    enabled=1\n    canary_line=&quot;server 127.0.0.1:5002 weight=${canary} max_fails=3 fail_timeout=10s;&quot;\nfi\ncat &gt;&quot;$candidate&quot; &lt;&lt;EOF\n# generation: $generation\nupstream app_pool {\n    zone app_pool 64k;\n    keepalive 16;\n    server 127.0.0.1:5001 weight=${stable} max_fails=3 fail_timeout=10s;\n    $canary_line\n}\nmap \\$host \\$canary_enabled { default $enabled; }\nmap \\$host \\$canary_generation { default &quot;$generation&quot;; }\nEOF\nchmod --reference=&quot;$STATE&quot; &quot;$candidate&quot;\nchown --reference=&quot;$STATE&quot; &quot;$candidate&quot;\n# Every config writer\/reloader must obey the same lock during this transaction.\n# Mark dirty before rename so a catchable signal cannot skip restoration.\ndirty=1\nmv -fT -- &quot;$candidate&quot; &quot;$STATE&quot;\nif ! nginx -t; then echo &quot;Candidate validation failed&quot; &gt;&amp;2; exit 1; fi\nif ! timeout 30 systemctl reload nginx; then echo &quot;Reload command failed&quot; &gt;&amp;2; exit 1; fi\nif ! wait_generation &quot;$generation&quot;; then echo &quot;New generation not observed&quot; &gt;&amp;2; exit 1; fi\ndirty=0\necho &quot;Accepted generation=$generation stable=$stable canary=$canary; verify traffic and draining workers.&quot;\n<\/code><\/pre>\n<p>The candidate replaces the state file by a same-directory atomic rename. If validation, reload or generation observation fails, the EXIT handler restores the previous file and attempts to reload\/observe its generation. Exit 1 reports a failed change; exit 2 reports unconfirmed restoration and retains the backup for manual disk\/runtime reconciliation. A successful generation probe proves only that a worker using that generation replied: old workers can briefly still accept connections and continue in-flight work. This is not a transaction against SIGKILL, power loss or unrelated administrators; monitor convergence and test restoration before rollout. Here GNU timeout sends its default TERM signal after 30 seconds; without -k this is not a hard 30-second completion bound. Terminating the systemctl client does not prove that a manager-owned reload job was canceled. Bash can defer a trapped signal while waiting for a foreground command. If the oneshot service exceeds its 180-second startup limit, systemd normally terminates its control group and may later force-kill remaining processes; restoration may be interrupted. Inspect the service state, retained backup and running generation, and prepare for manual recovery.<\/p>\n<h2 id=\"section-9\"><span id=\"Compare_Canary_and_Stable_Observations\">Compare Canary and Stable Observations<\/span><\/h2>\n<p>Track real canary sample count, client-facing errors, upstream attempt errors and latency in the same bounded window. The following commands consume the window file created earlier and require jq. They are inspection tools, not complete alerting or statistical rollout decisions.<\/p>\n<p>Count final client statuses where the last responding application identified itself as v2. This intentionally excludes canary failures that retried successfully on v1; inspect attempt records separately:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">jq -r &#039;select(.release == &quot;v2&quot;) | .status&#039; .\/canary-window.jsonl | sort | uniq -c\n<\/code><\/pre>\n<p>Inspect the largest total request times for final v2 responses, then repeat with v1 over the same interval. These include more than backend execution time; a few maxima neither establish a percentile nor prove a regression:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">jq -r &#039;select(.release == &quot;v2&quot;) | .request_time&#039; .\/canary-window.jsonl | sort -n | tail\n<\/code><\/pre>\n<p>Inspect all records that attempted the exact canary address, retaining the whole address\/status sequence. This example splits the comma-separated list for the shown configuration; if your application or error handling adds internal redirects between groups, normalize Nginx\u2019s colon-separated group structure before applying it. A matching line is not itself a retry count:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">jq -r &#039;select(.upstream | split(&quot;,&quot;) | map(gsub(&quot;^ +| +$&quot;; &quot;&quot;)) | index(&quot;127.0.0.1:5002&quot;))\n       | [.upstream, .upstream_status, .release, .status] | @tsv&#039; .\/canary-window.jsonl\n<\/code><\/pre>\n<p>Keep raw upstream addresses and variable-length attempt lists as log fields. Do not export every distinct list, request ID, user, IP or URL as a Prometheus label. If metrics are needed, normalize into bounded values such as stable\/canary\/unknown and a small status-class set, while retaining appropriate attempt accounting. Each label combination creates a time series with resource cost. The example access log omits paths, query strings, cookies, client IPs and user agents; audit other logs and their retention separately.<\/p>\n<h2 id=\"section-10\"><span id=\"A_Measured_Canary_Rollout\">A Measured Canary Rollout<\/span><\/h2>\n<p>Use this as a starting cadence, adjusting observation periods to traffic volume and risk:<\/p>\n<p>Before starting, confirm both process identities, the exact readiness response, trusted release headers, private backend reachability, capacity, logging and the timer. Test failed validation\/reload and the retained-backup recovery path in an isolated environment. Directly test v2 before enabling any public traffic; a static proxy health endpoint is insufficient.<\/p>\n<p>Step 1: enable weight 1 against stable 100, approximately 0.99% for eligible weighted requests. Verify actual v2 responses and exercise important flows with controlled test data. Wait for the predetermined sample size and health\/latency criteria, rather than assuming a few quiet minutes prove success.<\/p>\n<p>Step 2: consider weight 5, approximately 4.76%, only if the previous stage meets its criteria. Compare with stable during the same window; inspect retry attempts as well as successful final responses.<\/p>\n<p>Step 3: weights 10 and 20 target approximately 9.09% and 16.67%, respectively. Recheck login, forms, pagination, queue processing and database connections as relevant. Use authorized test transactions that avoid unintended real payments, messages or inventory changes.<\/p>\n<p>Step 4: weight 50 against stable 100 targets roughly one-third, not half. Observe enough actual canary requests and important operations; check latency distributions and resource saturation. Stop or roll back when agreed criteria fail, even if the basic readiness endpoint still passes.<\/p>\n<p>Step 5: promote v2 only after sufficient observation. With stable still at weight 100, canary weight 100 is approximately a 50\/50 split, not all-in. Before promotion, stop the health-check timer, wait for any already-running guard\/helper invocation to finish, and verify its result and the running configuration. The existing helper regenerates the old backend addresses; running it unchanged after promotion can route traffic back to v1. Full promotion requires removing v1 from active routing, validating and reloading the configuration under the shared lock, and allowing existing work to drain before stopping v1. Keep v1 available for rollback while compatibility permits. Before re-enabling the timer, adapt the helper targets, guard release\/port contract and initial state file to the next rollout\u2019s stable\/canary layout, then test disable and recovery. Low traffic calls for more observation, not automatically skipping stages.<\/p>\n<h2 id=\"section-11\"><span id=\"Session_Cache_and_Database_Compatibility\">Session, Cache and Database Compatibility<\/span><\/h2>\n<p>Both versions must understand the same session state. A shared Redis\/database store alone is insufficient: verify serialization, cookie names\/scopes, signing or encryption keys, authentication and CSRF behavior across versions. An IP hash cannot preserve continuity when addresses or upstreams change. Fix compatibility before relying on routing affinity.<\/p>\n<p>Cache keys and values must remain readable by both versions during coexistence. If the format changes incompatibly, isolate it with versioned keys and test invalidation and fallback behavior. Delay cleanup until old readers and their rollback window are retired; a shared cache alone does not establish compatibility.<\/p>\n<p>Use backward-compatible database changes and postpone destructive cleanup until the rollback window closes. Adding a column\/table is not automatically safe: defaults, constraints, migration locks and new write formats can still break v1. Verify both readers and writers. Restoring a pre-release snapshot can discard later writes, so plan data recovery separately from traffic rollback. The <a href=\"https:\/\/www.dchost.com\/blog\/en\/the-little-freeze-that-saves-your-data-application-consistent-hot-backups-with-lvm-snapshots-for-mysql-and-postgresql\/\">application-consistent LVM backup guide<\/a> covers backup preparation; perform an actual recovery test for your database setup.<\/p>\n<h2 id=\"section-12\"><span id=\"Optional_Hash_Buckets_with_split_clients\">Optional Hash Buckets with split_clients<\/span><\/h2>\n<p>The following alternative replaces the entire cookie\/weighted routing map in the main http fragment. Keep the fixed app_stable\/app_canary upstreams, shared state include and proxy server; do not add duplicate maps or disconnected v1\/v2 pools. Cookie overrides no longer apply. The shared gate still disables all selected canary buckets:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\"># Alternative to the cookie\/weighted routing map, inside http.\n# Keep the shared state include, fixed app_stable\/app_canary pools and proxy server.\nsplit_clients &quot;$remote_addr|$http_user_agent&quot; $bucket {\n    5% canary;\n    *  stable;\n}\nmap &quot;$canary_enabled:$bucket&quot; $backend_upstream {\n    default    app_stable;\n    &quot;1:canary&quot; app_canary;\n}\n<\/code><\/pre>\n<p>The <a href=\"http:\/\/nginx.org\/en\/docs\/http\/ngx_http_split_clients_module.html\" rel=\"nofollow noopener\" target=\"_blank\">official split_clients documentation<\/a> describes MurmurHash2 allocation of hash-space ranges. Here 5% of that space selects canary only while enabled. Identical IP\/User-Agent inputs stay in the same bucket under the unchanged rule, but IPs can be shared or change and user agents can change. This does not promise 5% of users or requests. A suitable stable application identifier can improve cohort consistency, with appropriate privacy and authentication controls. Helper weights do not change the 5% bucket size; changing it is a separate controlled config update.<\/p>\n<h2 id=\"section-13\"><span id=\"TLS_and_Graceful_Reload_Limitations\">TLS and Graceful Reload Limitations<\/span><\/h2>\n<p>Adapt the HTTP routing example to your existing HTTPS server and verify certificate renewal, service reload and client connectivity. Graceful reload starts new workers and asks old ones to finish existing clients; it does not guarantee warmed connections or immediate draining. Observing a new generation can precede old listening sockets closing. Monitor the transition, retain old application processes while needed, and coordinate automated reloads with the same lock.<\/p>\n<p>Behind a CDN or tunnel, direct loopback readiness checks help distinguish the canary application from cached or edge responses. Also test the real user path, Host\/scheme forwarding, cache isolation and TLS separately. A healthy local response cannot establish end-to-end availability.<\/p>\n<h2 id=\"section-14\"><span id=\"Retry_and_Timeout_Tradeoffs\">Retry and Timeout Tradeoffs<\/span><\/h2>\n<p>Limited retries may help certain transient failures, but can increase load, mask canary problems behind a successful stable response or duplicate effects if application semantics are unsafe. Observe actual attempt lists and adjust retry and timeout settings to the workload.<\/p>\n<p>The shown configuration allows error, timeout and HTTP 502\/503\/504 conditions with at most two total attempts. It does not enable non_idempotent retries. A response already sent to the client cannot be repaired by switching peers. Single-peer forced\/hash paths cannot retry on stable within their own pool. The guard\u2019s three failed probes initiate a later config transition; they do not cancel requests already executing.<\/p>\n<p>Review the <a href=\"http:\/\/nginx.org\/en\/docs\/http\/ngx_http_upstream_module.html\" rel=\"nofollow noopener\" target=\"_blank\">upstream documentation<\/a> and proxy retry semantics against your actual application. Rate\/error budgets, circuit breakers and idempotency controls may complement the routing layer, but none should be assumed from this sample alone.<\/p>\n<h2 id=\"section-15\"><span id=\"Protect_Control_Scripts_and_Private_Endpoints\">Protect Control Scripts and Private Endpoints<\/span><\/h2>\n<p>Keep administration authenticated and backend\/config-probe ports private. A canary cookie is a client preference, not authorization. Limit readiness output, protect helper\/state\/unit ownership, and prevent unauthorized changes to the command search path used by privileged scripts. Configure log access, retention and rotation according to actual operational needs; the minimal access log does not sanitize other application or error logs.<\/p>\n<h2 id=\"section-16\"><span id=\"Common_Canary_Configuration_Errors\">Common Canary Configuration Errors<\/span><\/h2>\n<p>First, verify weight arithmetic against the currently configured stable baseline. 1:1 is approximately half; stable 100\/canary 50 is approximately one-third. Validate exact positive integers and use down for disabling. Do not infer the deployed ratio from a helper command without checking active config and actual release samples.<\/p>\n<p>Second, check keepalive behavior for the installed Nginx version. The weighted app_pool explicitly sets an idle cache of 16; fixed single-peer pools use that version\u2019s defaults. Current documentation describes defaults changing in 1.29.7. HTTP\/1.1 and a cleared Connection header support reuse, but do not prove connections remain warm through a reload. The idle cache limit is not a cap on all open upstream connections; measure behavior before tuning.<\/p>\n<p>Third, verify sessions across versions instead of assuming shared storage or a cookie route solves continuity. Check cookie scope, serialization, key rotation and authentication behavior. Hash buckets can change when inputs or the rule change; they are not a substitute for compatibility.<\/p>\n<p>Fourth, delay destructive database changes and test even additive migrations for constraints, defaults, write formats and locking. Keep cache formats mutually readable or version their keys. Rollback is useful only while v1 can handle the current data and session state.<\/p>\n<h2 id=\"section-17\"><span id=\"A_Canary_Rollout_Checklist\">A Canary Rollout Checklist<\/span><\/h2>\n<p>Adapt this checklist to your application, traffic and recovery requirements:<\/p>\n<p>Prepare: separately managed v1\/v2 processes, spare capacity, exact readiness contracts, release identity, private ports, shared state include, JSON logs, compatible data\/sessions\/cache, and tested helper restoration. Install both executable scripts and separate units, daemon-reload, enable &#8211;now the timer, then inspect its status and service journal.<\/p>\n<p>Ship: enable the smallest suitable share, confirm real canary observations, test controlled critical operations and compare with stable. Increase only after the sample\/health criteria pass. Monitor resource saturation and side effects as well as HTTP errors.<\/p>\n<p>Hold: run <code>canary-weight.sh disable<\/code> when criteria fail, inspect its exit status and verify routing convergence and old work draining. The helper already reloads. If restoration is unconfirmed, preserve its backup and reconcile runtime\/disk state; investigate and validate a fix before reopening traffic.<\/p>\n<p>Finish: perform a separate controlled promotion that makes v2 the stable destination; stable 100\/canary 100 still leaves v1 selected. Keep v1 available during the compatible rollback window, then wait for old work to drain before stopping it. Prepare and test the next rollout state without deleting the required include.<\/p>\n<h2 id=\"section-18\"><span id=\"Feature_Flags_and_Other_Canary_Changes\">Feature Flags and Other Canary Changes<\/span><\/h2>\n<p>Feature flags can separately control a risky code path within a canary release. Validate flag targeting and defaults so the observed cohort actually exercises the intended path. Configuration or cache changes can also be tested in the canary process when both versions remain compatible.<\/p>\n<p>Frontend infrastructure changes need their own isolation boundary. A shared TLS or compression setting applied to the public Nginx server may affect every request before upstream canary selection. Use a separate controlled listener, hostname or edge cohort where appropriate; changing backend weights alone does not canary the TLS handshake.<\/p>\n<h2 id=\"section-19\"><span id=\"Complete_the_Rollout_with_Verified_Evidence\">Complete the Rollout with Verified Evidence<\/span><\/h2>\n<p>A single-VPS canary combines two compatible application versions, explicit routing state, meaningful readiness checks and a tested traffic return path. Its value comes from observing enough actual canary work and acting on agreed stop criteria. Shared-host failures, completed side effects and data recovery remain separate concerns.<\/p>\n<p>Start disabled, validate the exact examples in your own environment, install and inspect the timer, then open a measured share. Keep weighted, cookie and optional hash routes under the same gate. Use bounded log fields for analysis and bounded label values for metrics. Neither one healthy endpoint nor one successful reload proves complete readiness or traffic convergence.<\/p>\n<p>Before retiring v1, confirm full promotion, compatibility and draining. Preserve the recovery procedure and enough operational evidence to investigate errors; choose retention and access rules for the data actually logged. Plan traffic rollback, application rollback and data restoration as distinct operations.<\/p>\n<h2 id=\"section-20\"><span id=\"Nginx_Reference_Documentation\">Nginx Reference Documentation<\/span><\/h2>\n<p>If you want to dive deeper into the Nginx knobs we used, the official docs for <a href=\"http:\/\/nginx.org\/en\/docs\/http\/ngx_http_upstream_module.html\" rel=\"nofollow noopener\" target=\"_blank\">upstream configuration and health-related parameters<\/a> and the <a href=\"http:\/\/nginx.org\/en\/docs\/http\/ngx_http_split_clients_module.html\" rel=\"nofollow noopener\" target=\"_blank\">split_clients directive<\/a> are short and clear. For passive retry behavior, the proxying docs include <code>proxy_next_upstream<\/code> and friends, which are worth a skim before your next rollout.<\/p>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Roll out two application versions with Nginx. Validate weighted routing, a shared disable gate, readiness checks and recovery limits before increasing real canary traffic.<\/p>\n","protected":false},"author":1,"featured_media":10572,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[184],"tags":[],"class_list":["post-1986","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/1986","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/comments?post=1986"}],"version-history":[{"count":1,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/1986\/revisions"}],"predecessor-version":[{"id":10574,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/1986\/revisions\/10574"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/media\/10572"}],"wp:attachment":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/media?parent=1986"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/categories?post=1986"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/tags?post=1986"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}