<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rameshkumar Shanmugam on Medium]]></title>
        <description><![CDATA[Stories by Rameshkumar Shanmugam on Medium]]></description>
        <link>https://medium.com/@rameshkumarsgp?source=rss-c078d297bcc3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Ek-IZ0wAUNYGkbh5.</url>
            <title>Stories by Rameshkumar Shanmugam on Medium</title>
            <link>https://medium.com/@rameshkumarsgp?source=rss-c078d297bcc3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:37:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rameshkumarsgp/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a forward proxy with Caddy: HTTPS CONNECT and outbound traffic control]]></title>
            <link>https://medium.com/@rameshkumarsgp/building-a-forward-proxy-with-caddy-https-connect-and-outbound-traffic-control-209f03a2ea7c?source=rss-c078d297bcc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/209f03a2ea7c</guid>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[caddy]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rameshkumar Shanmugam]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 06:53:02 GMT</pubDate>
            <atom:updated>2026-11-27T06:53:02.986Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 5. It follows the NAT Gateway and Elastic IP article, which explained how a private service gets a fixed outbound address. This one is about controlling where that traffic may go.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPAqqo4IoHPTHKYucMOn8g.png" /></figure><p>Introduction</p><p>Caddy is known as a web server and a reverse proxy. A reverse proxy sits in front of your servers and receives requests on their behalf. A <strong>forward proxy</strong> is the other way round: it sits in front of your <em>clients</em> and makes requests on their behalf.</p><p>The stock Caddy download does <strong>not</strong> contain a general-purpose forward proxy. Its reverse_proxy directive forwards requests to servers you list in the config, and not to any host a client names. For the second job there is a community module, <strong>forwardproxy</strong>, maintained under the caddyserver organisation on GitHub. This article explains what it adds, how an HTTPS request travels through it, and how to deploy it so that it does not become an open door.</p><p>The running example is a document service on AWS that calls external providers. One point first, because it is easy to get wrong: <strong>a forward proxy is not needed for every fixed-IP requirement.</strong> A NAT gateway with an Elastic IP already provides a fixed address. A proxy is justified only when you also need to control or record where outbound traffic goes. Sections 9 and 10 return to this.</p><h3>Caddy reverse proxy versus forward proxy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNDK_lNwOE5D5lR6SYLFUA.png" /></figure><p>Reverse proxy (stock Caddy)Forward proxy (plugin build)Traffic directionInbound: from many clients to your serversOutbound: from your clients to external serversWho knows the destinationThe Caddyfile. Clients know only the proxy’s addressThe client. It names the destination in each requestMain responsibilityRouting, load balancing, TLS for your siteDeciding which destinations a client may reach, and on whose authorityClient configurationNone. It is a normal website to the clientThe client must be told to use the proxy (for example HTTPS_PROXY)</p><p>The plugin registers a new HTTP handler module, http.handlers.forward_proxy. In the Caddyfile it appears as the forward_proxy directive. Caddy still provides the listeners, logging and configuration, and the plugin adds the proxy behaviour.</p><h3>Understanding the forwardproxy plugin</h3><h3>What it provides</h3><p>According to the project’s README it supports HTTP/1.1, HTTP/2 and HTTP/3 between client and proxy, authentication, access control lists, optional probe resistance (hiding that the server is a proxy) and PAC file serving. This article uses authentication and access control lists, the parts that matter for controlling outbound traffic from a service.</p><p><strong>Read this before you depend on it:</strong> the README marks the module <strong>experimental</strong> and warns to expect breaking changes. The repository’s latest tagged release is very old (2019), and current development happens on the main branch. Check the project page for the state of things before you publish or deploy, and pin the exact version you tested.</p><h3>Why a custom build is needed</h3><p>Caddy’s modules are compiled into the single binary (Article 1). Stock Caddy includes the standard ones, and community modules such as this one are not part of it. You need a binary built with the module.</p><h3>Building with xcaddy</h3><p>xcaddy is Caddy&#39;s build tool. It compiles Caddy together with the modules you name. It needs a recent Go toolchain (the plugin&#39;s README asks for Go 1.20 or later).</p><pre>xcaddy build --with github.com/caddyserver/forwardproxy</pre><p>This produces a caddy binary in the current folder. Check that the module is present:</p><pre>./caddy list-modules | grep forward_proxy<br># http.handlers.forward_proxy</pre><p>To make the build repeatable, pin a version or commit: --with github.com/caddyserver/forwardproxy@&lt;commit-or-tag&gt;. You can also select the module on Caddy&#39;s download page, which builds a binary for you.</p><p>For containers, the official pattern is a multi-stage Dockerfile:</p><pre>FROM caddy:2-builder AS builder<br>RUN xcaddy build --with github.com/caddyserver/forwardproxy</pre><pre>FROM caddy:2<br>COPY --from=builder /usr/bin/caddy /usr/bin/caddy</pre><ul><li>The first stage uses the image that has Go and xcaddy and builds the custom binary.</li><li>The second stage starts from the normal small Caddy image and replaces its binary with the custom one.</li></ul><p><strong>Stock Caddy and plugin Caddy are different programs.</strong> A Caddyfile that uses forward_proxy fails to load on stock Caddy with an unknown directive error. Keep the two clearly separate in your images and in your documentation, so that nobody replaces the proxy with a stock image by accident.</p><h3>How HTTPS CONNECT works</h3><p>A browser or program that uses a proxy for HTTP sends the whole request to the proxy, which can read it. HTTPS must not work that way, because the content is encrypted for the destination and not for the proxy. HTTP solves this with a method called <strong>CONNECT</strong>, which asks the proxy to open a tunnel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXdf1LhO869BbMhDPfzW4A.png" /></figure><ol><li><strong>The client connects to the forward proxy</strong> (for example on port 3128).</li><li><strong>It sends </strong><strong>CONNECT api.provider-a.example.com:443</strong>, with its proxy credentials in the Proxy-Authorization header.</li><li><strong>The proxy checks the request.</strong> Are the credentials valid, is the port permitted, does the destination host resolve to an address the rules allow, and is the host on the allow-list? If any check fails the proxy answers with an error and does nothing else (407 for missing or wrong credentials, an error status such as 403 for a destination that is not allowed).</li><li><strong>The proxy opens an outbound TCP connection</strong> to the destination, from its own address, and replies 200 Connection established.</li><li><strong>The client starts the TLS handshake with the destination</strong> through the tunnel. From here on the proxy copies encrypted bytes in both directions.</li></ol><h3>What the proxy can and cannot inspect</h3><ul><li><strong>It can see:</strong> the destination host name and port in the CONNECT line, the client’s address, the credentials, when the tunnel opened and closed, and how much data moved.</li><li><strong>It cannot see:</strong> the URL path, the headers, the request or response body, or any other content of the HTTPS session, because the TLS session runs end to end between client and provider. The proxy does not hold a certificate for the provider, and it does not decrypt (this article does not use TLS interception).</li></ul><p>That is a useful property. A proxy can enforce <em>which hosts</em> may be reached and log them, without ever holding the content, such as the documents the service fetches. It also means the proxy cannot enforce rules on paths or methods for HTTPS traffic.</p><h3>Configuring the Caddy forward proxy</h3><h3>A first, unsafe example</h3><p>The README’s smallest configuration looks like this, and it is labelled “unauthenticated, use only for testing”:</p><pre>{<br>    order forward_proxy first<br>}</pre><pre>:3128 {<br>    forward_proxy<br>}</pre><ul><li>order forward_proxy first: Caddy runs directives in a fixed order, and a plugin directive needs a place in it. The plugin&#39;s default is after file_server. Putting it first makes sure that nothing else handles the request before the proxy does.</li><li>:3128: a site address with no host name, so it matches requests for any destination. Proxy requests name other hosts, and a site tied to one host name would not match them. The README points out that addresses must be of this catch-all kind (it uses :443) for the proxy to handle requests for all origins.</li><li>forward_proxy: turns the site into a proxy. It handles CONNECT for HTTPS and absolute-URL requests for plain HTTP.</li></ul><p>Anyone who can reach port 3128 can use this to reach any host on the internet from your address. Do not run it as it is, except on your own machine for a test.</p><h3>Authentication, allow-list and ports</h3><pre>{<br>    order forward_proxy first<br>    auto_https off<br>}</pre><pre>:3128 {<br>    log {<br>        output stdout<br>        format json<br>    }</pre><pre>    forward_proxy {<br>        basic_auth doc_service {env.PROXY_PASSWORD}<br>        ports 443<br>        dial_timeout 10s</pre><pre>        acl {<br>            deny 10.0.0.0/8 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.168.0.0/16 ::1/128 fe80::/10<br>            allow api.provider-a.example.com<br>            allow *.provider-b.example.com<br>            deny all<br>        }<br>    }<br>}</pre><ul><li>auto_https off: this proxy serves plain HTTP inside the private network, and Caddy should not try to obtain certificates (Article 2).</li><li>log { output stdout, format json }: access logs as JSON on standard output, to be collected by the container runtime.</li><li>basic_auth doc_service {env.PROXY_PASSWORD}: requires a user name and password from every client. This is the <em>plugin&#39;s own</em> basic_auth option inside forward_proxy, not Caddy&#39;s built-in basic_auth directive. The value comes from an environment variable so that the secret stays out of the file. Repeat the option for more users, one per calling service, so that you can tell them apart and revoke one.</li><li>ports 443: only port 443 may be requested. Everything else is refused.</li><li>dial_timeout 10s: how long the proxy waits when opening the connection to the destination (the default is 30 seconds).</li><li>acl { ... }: access control rules for destinations, checked in order, and the first one that matches decides. The proxy resolves the requested host name to an address, and checks both the name and the address against the rules.</li><li>The first rule denies private, loopback and link-local ranges. This is explained in the next section: it stops the proxy from being used to reach your internal network. Per the README, hostname rules placed earlier override later IP rules, so IP rules go first.</li><li>allow api.provider-a.example.com allows exactly that host. allow *.provider-b.example.com allows that domain and its sub-domains.</li><li>deny all refuses everything not matched. Without a closing rule, unmatched requests fall back to the plugin&#39;s default policy, which ends in &quot;allow all&quot;.</li></ul><p>The client-to-proxy hop in this example is plain HTTP, and the proxy password crosses the private subnet unencrypted. Inside a tightly controlled private subnet that is often accepted. If your rules do not allow it, serve the proxy over TLS (the README shows the form :443, proxy.example.com). Use a certificate the clients trust, for example from Caddy&#39;s internal CA (Article 2) with its root installed on the client.</p><p>The plugin documentation says its syntax is subject to change. Always test with the version you build.</p><h3>Client configuration with HTTPS_PROXY</h3><p>Most HTTP libraries read the standard environment variables. Set them for the Doc service:</p><pre>export HTTPS_PROXY=http://doc_service:PASSWORD@10.0.11.50:3128<br>export NO_PROXY=localhost,127.0.0.1,.internal.example</pre><ul><li>HTTPS_PROXY says where to send HTTPS requests. The URL scheme describes the hop to the proxy (here http), not the destination. It carries the proxy credentials. URL-encode any special characters in the password.</li><li>NO_PROXY lists hosts that should be reached directly, such as local services and internal names.</li></ul><p>Not every client honours these variables. Go’s net/http and Python&#39;s requests do by default. Node.js and Java need explicit settings (for Java, the https.proxyHost and https.proxyPort system properties, or a proxy-aware client). Check your client library.</p><h3>Testing with curl</h3><pre># An allowed host, through the proxy<br>curl -v -x http://doc_service:PASSWORD@10.0.11.50:3128 https://api.provider-a.example.com/health</pre><pre># A host that is not on the allow-list<br>curl -v -x <a href="http://doc_service:PASSWORD@10.0.11.50:3128/">http://doc_service:PASSWORD@10.0.11.50:3128</a> <a href="https://example.org/">https://example.org/</a></pre><pre># No credentials<br>curl -v -x <a href="http://10.0.11.50:3128/">http://10.0.11.50:3128</a> <a href="https://api.provider-a.example.com/health">https://api.provider-a.example.com/health</a></pre><pre># Which address do outsiders see?<br>curl -x <a href="http://doc_service:PASSWORD@10.0.11.50:3128/">http://doc_service:PASSWORD@10.0.11.50:3128</a> <a href="https://checkip.amazonaws.com/">https://checkip.amazonaws.com</a></pre><ul><li>-x (or --proxy) names the proxy. -v shows the CONNECT line and the proxy&#39;s answer.</li><li>The first call should succeed. The second should be refused by the proxy. The third should get 407.</li><li>The last call should print the NAT gateway’s Elastic IP, which shows that the fixed address comes from the egress path.</li></ul><p>The first two use hosts from the Caddyfile and an example host. Replace them with your own.</p><h3>Security considerations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKJd9G8E78wraG9OhjWlWw.png" /></figure><ul><li><strong>Never run an open forward proxy.</strong> An unauthenticated proxy reachable from outside will be found by scanners within hours. They will use it to hide abusive traffic, and the traffic will carry <em>your</em> Elastic IP. That can get the address blocked, which breaks the integration the address was meant to protect.</li><li><strong>Restrict who can connect.</strong> Allow port 3128 only from the Doc service’s security group, with no rule for the internet. The proxy lives in a private subnet.</li><li><strong>Require authentication.</strong> It adds a second barrier if another workload in the VPC is compromised, and one credential per calling service lets you revoke a single service.</li><li><strong>Restrict destinations.</strong> An allow-list of hosts, ending with deny all, limits what a compromised service can reach. Allow only the HTTPS port.</li><li><strong>Consider DNS resolution and destination IPs.</strong> The proxy resolves names itself, so an allowed name could point at an internal address, by mistake or by an attacker. Deny private ranges first. Include 169.254.0.0/16 explicitly: it contains the EC2 instance metadata address 169.254.169.254, and I did not find it in the plugin&#39;s default list of denied ranges. A proxy that can reach it could be used to read the instance&#39;s credentials. Also require IMDSv2 on the proxy instances.</li><li><strong>Monitor and audit.</strong> Ship the JSON log to CloudWatch Logs. Review which service asked for which host, and alarm on refused requests and on spikes. Check what the log actually records for CONNECT requests in your version before you rely on it as an audit source.</li><li><strong>Keep the build current.</strong> The module is experimental. Rebuild regularly with the current Caddy and watch the project for security fixes.</li></ul><h3>Caddy forward proxy versus Squid</h3><p>Caddy with forwardproxySquidConfigurationA few lines in the Caddyfile, familiar if you already use CaddyIts own configuration language, with many optionsMaturityThe module’s README calls it experimental and expects breaking changesA long-established proxy, widely deployed, well documentedAuthenticationBasic authentication, built into the moduleSeveral schemes through helper programs (basic, LDAP and others)LoggingCaddy’s structured (JSON) logsDetailed access logs with configurable formats, and a large tooling ecosystemAccess controlsHost and IP rules in an ordered list, a port listRich ACLs: source, destination, time, method, port and combinationsOperational requirementsA custom Caddy build to maintain and rebuildA distribution package, updated by the usual meansProduction suitabilityReasonable for a small, simple allow-list if you accept the experimental status and test your own versionThe conservative choice for a critical outbound control</p><p>Neither is better in every case. If your team already runs Caddy and the need is a short list of hosts, the plugin is easy to operate. If the proxy is a central, compliance-relevant control with complex rules, Squid’s maturity counts for more. A managed alternative, AWS Network Firewall, can filter outbound traffic by domain without a proxy to run.</p><h3>Deploying Caddy as a forward proxy on AWS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwBL7-CK60zhaCI8TJRI8g.png" /></figure><h3>A dedicated proxy service</h3><p>Run the proxy as its own service on its own instance or container, not on the same machine as the application, so that it can be secured, logged, updated and scaled separately. One Docker Compose service is enough on an instance:</p><pre>services:<br>  forward-proxy:<br>    image: 123456789012.dkr.ecr.ap-south-1.amazonaws.com/caddy-forward-proxy:2.0.0<br>    restart: unless-stopped<br>    ports:<br>      - &quot;3128:3128&quot;<br>    environment:<br>      PROXY_PASSWORD: ${PROXY_PASSWORD}<br>    volumes:<br>      - ./Caddyfile:/etc/caddy/Caddyfile:ro<br>      - caddy_data:/data<br>      - caddy_config:/config</pre><pre>volumes:<br>  caddy_data:<br>  caddy_config:</pre><ul><li>The image is the custom build from the Dockerfile above, pushed to your own registry and tagged with a version.</li><li>Port 3128 is published to the instance and nowhere else.</li><li>PROXY_PASSWORD comes from the deploy environment, which should read it from AWS Secrets Manager or Parameter Store, not from a file in the repository.</li></ul><h3>Security groups and private network access</h3><ul><li><strong>Proxy security group:</strong> inbound TCP 3128 from the Doc service’s security group only. Outbound TCP 443 to the internet.</li><li><strong>Doc service security group:</strong> outbound TCP 3128 to the proxy’s security group, plus whatever else the service needs.</li><li>Both live in private subnets and have no public address.</li></ul><h3>Outbound path: NAT gateway and Elastic IP</h3><p>The proxy’s route table sends 0.0.0.0/0 to a NAT gateway in a public subnet. The NAT gateway&#39;s Elastic IP is the address that providers allow-list. <strong>The proxy does not create, replace or manage that address.</strong> The NAT gateway and Elastic IP stay separate pieces of infrastructure, exactly as in the previous article, and everything there about one gateway per zone, several addresses and the allow-list still applies. Run a proxy in each zone and point each zone&#39;s service at its local proxy, or put an internal Network Load Balancer in front of the proxies. A single proxy instance is a new single point of failure.</p><h3>Application configuration</h3><p>Give the Doc service HTTPS_PROXY and NO_PROXY as shown earlier, through its task or container environment. Use the proxy&#39;s private DNS name instead of an IP address, so that you can replace the instance.</p><h3>When to use Caddy forward proxy</h3><ul><li><strong>Centralised outbound access.</strong> Many services need to call out, and you want one place for the rules and the credentials.</li><li><strong>Destination hostname restrictions.</strong> A policy says a service may reach only named hosts, and a NAT gateway cannot enforce that.</li><li><strong>Proxy-based audit requirements.</strong> You must be able to show which service contacted which external host and when.</li><li>You already run Caddy, the rules are short, and you accept the plugin’s experimental status after testing it.</li></ul><h3>When not to use it</h3><ul><li><strong>You only need a fixed outbound IP.</strong> A NAT gateway with an Elastic IP does that on its own. A proxy adds nothing to the address, and adds a component to run.</li><li><strong>Simple outbound API connectivity.</strong> A service calling two or three providers needs routes and security groups, not a proxy.</li><li><strong>NAT gateway and security controls already meet the requirement.</strong> Egress rules on security groups and VPC Flow Logs may be all the control and evidence you are asked for.</li><li><strong>You need a mature, heavily supported control</strong> and cannot accept an experimental module. Consider Squid or AWS Network Firewall instead.</li></ul><h3>Conclusion</h3><p>A forward proxy and a reverse proxy are different tools with opposite traffic directions. Stock Caddy is a reverse proxy. With the community forwardproxy module and a custom build made with xcaddy, it also becomes a forward proxy that understands HTTPS CONNECT: it can check who is calling and which host is requested, and it opens an encrypted tunnel without seeing what travels through it.</p><p>Introducing one is justified when you must control or record <em>where</em> outbound traffic goes. If the only requirement is <em>which address</em> it comes from, the NAT gateway and Elastic IP from the previous article are enough. If you do deploy the proxy, treat it as a security component: authenticated, reachable only from the services that need it, limited to named hosts and ports, protected from internal and metadata addresses, and logged.</p><p><em>Before publishing, check the forwardproxy repository for current syntax, the supported Caddy versions and its experimental status.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=209f03a2ea7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS NAT Gateway and Elastic IP: fixed outbound IPs for backend services]]></title>
            <link>https://medium.com/@rameshkumarsgp/aws-nat-gateway-and-elastic-ip-fixed-outbound-ips-for-backend-services-049eeb9c4d53?source=rss-c078d297bcc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/049eeb9c4d53</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Rameshkumar Shanmugam]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 06:43:17 GMT</pubDate>
            <atom:updated>2026-11-27T06:43:17.315Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 4. This article stands on its own: it is about outbound traffic, and it does not need the reverse proxy articles. Where it touches them, it says so.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlBxW_1RGCXYq3emMxvGFQ.png" /></figure><h3>Introduction</h3><p>Most backend services call other systems. Our running example is a document service that fetches documents from external providers such as DigiLocker and Protean. Each call leaves your network, crosses the internet and arrives at the provider’s servers.</p><p>Some providers will accept those calls only from addresses they know. During onboarding they ask for the public IP addresses your calls will come from, and they add them to an <strong>allow-list</strong>. A call from any other address is refused before it reaches the application. (What each provider requires differs, so read the provider’s onboarding documents. The pattern is common enough to plan for.)</p><p>That means the address your calls come from must be <strong>stable</strong>. If it changes without warning, every call fails until the provider updates the list, which can take days. This article shows how AWS gives a private backend a stable, predictable public address for outbound traffic, and how to build it so that a failure does not break the integration.</p><h3>Understanding private and public IP addresses</h3><h3>Private IP addresses</h3><p>A private IP address comes from ranges reserved for internal use: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. They work only inside a network. Thousands of networks use the same private addresses, so an address such as 10.0.11.25 says nothing about whose server it is.</p><h3>Public IP addresses</h3><p>A public IP address is unique on the internet. Packets can be routed to it from anywhere, and it identifies a specific owner.</p><h3>Why EC2 instances usually have only private IPs</h3><p>An application server in a private subnet has no public address on purpose. Nothing on the internet can start a connection to it, which removes a large class of attacks. The same instance can still call out, through a device that handles the public side.</p><h3>Why a provider cannot identify a private IP</h3><p>If the instance sent a packet with source 10.0.11.25, the provider could not reply, because that address is not routable on the internet. And even if it could, the address would not identify you, since a million other networks use it. Something has to replace the private source address with a public one. That is NAT.</p><h3>Understanding NAT</h3><p><strong>Network Address Translation</strong> rewrites addresses in packets as they pass through a device. The form used here is source NAT: the device replaces the <em>source</em> address of outbound packets with its own public address.</p><h3>Why it is needed</h3><p>Many private hosts must share a small number of public addresses, and private hosts must reach the internet without being reachable from it.</p><h3>Source translation, and how replies find their way back</h3><p>For each outbound connection the NAT device records a mapping: the instance’s private address and port, and the public address and port it used instead. The reply comes back addressed to the public address and port. The device looks the pair up, rewrites the destination to the instance’s private address and port, and forwards the packet. Because the table is keyed by <strong>port</strong>, one public address can serve many instances at once. Replies to connections that the instance started are let through, but a new connection from the internet has no entry in the table and is dropped.</p><h3>What is AWS NAT Gateway?</h3><p>A <strong>NAT gateway</strong> is a managed AWS service that does this translation for a VPC. You do not run a server, patch it or size it. AWS scales it as traffic grows.</p><h3>Public and private NAT gateways</h3><ul><li>A <strong>public NAT gateway</strong> lets instances in private subnets reach the internet. It needs an Elastic IP and sits in a public subnet. It is the one this article is about.</li><li>A <strong>private NAT gateway</strong> has no Elastic IP and no route to the internet. It translates addresses for traffic to other VPCs or to on-premises networks, for instance when two networks use overlapping address ranges. It is a different tool for a different problem.</li></ul><h3>Public subnet and internet gateway</h3><p>The NAT gateway is created <strong>in a public subnet</strong>, which is a subnet whose route table sends 0.0.0.0/0 to an <strong>internet gateway</strong>. The internet gateway is the VPC&#39;s door to the internet. The NAT gateway gets its public address from its Elastic IP and sends the translated packets out through that door.</p><h3>Why private subnets route outbound traffic through it</h3><p>The private subnet’s route table sends 0.0.0.0/0 to the NAT gateway, not to the internet gateway. Every packet bound for the internet goes to NAT first and gets the public source address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQ9epIXZ0P8BdTeyh-aeFQ.png" /></figure><p>A NAT gateway lives in <strong>one Availability Zone</strong>. It is redundant inside that zone but does not span zones. Section 8 returns to this.</p><h3>Understanding Elastic IP</h3><p>An <strong>Elastic IP address</strong> (EIP) is a static public IPv4 address that you allocate to your AWS account. It belongs to your account until you release it. It is not tied to any instance, and you can associate it with a resource and later move it to another.</p><h3>How it is attached to a NAT gateway</h3><p>When you create a public NAT gateway you choose an EIP for it. All traffic the NAT gateway sends to the internet carries that address as its source.</p><h3>Why it stays the same</h3><p>The address is held by your account, so restarting, redeploying or replacing the instances behind NAT changes nothing. The provider sees the same address regardless of which instance made the call. That is what makes it suitable for an allow-list.</p><h3>Lifecycle: replacement and release</h3><ul><li><strong>Deleting a NAT gateway does not release its EIP.</strong> The address stays allocated to your account, and you are charged for it while it is not in use.</li><li><strong>Replacing a NAT gateway</strong> (for example to move it to another subnet) means creating a new NAT gateway and associating the <em>same</em> EIP. The allow-listed address does not change.</li><li><strong>The EIP of an existing NAT gateway cannot be swapped for a different primary one.</strong> To change the address you must create a new NAT gateway, and then you must tell the providers.</li><li><strong>Releasing an EIP</strong> returns it to AWS’s pool. You may not get it back, since someone else may be given it. Worse, if the provider’s allow-list still contains that address, another AWS customer now makes calls from an address your provider trusts. Release an address only after the providers have removed it.</li></ul><p>Treat the EIPs behind your integrations as long-lived infrastructure. Tag them with their purpose and owner, and protect them from accidental deletion with a process.</p><h3>Follow an outbound request</h3><p>Doc service on EC2 (10.0.11.25) calls the provider&#39;s API (198.51.100.50). The addresses here are documentation examples. The Elastic IP is 203.0.113.10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2iCcKu_WCbKp-iP-vbSZw.png" /></figure><p><strong>DNS resolution.</strong> The service first resolves the provider’s host name. The query goes to the VPC’s DNS resolver, not through the NAT gateway, and the answer is 198.51.100.50.</p><ol><li><strong>TCP connection.</strong> The instance sends a SYN from 10.0.11.25:51514 to 198.51.100.50:443. The private subnet&#39;s route table sends it to the NAT gateway. NAT records a mapping, rewrites the source to 203.0.113.10:1024 and forwards it through the internet gateway.</li><li><strong>HTTPS connection.</strong> The TLS handshake and the HTTPS request travel inside that same TCP connection, so they pass through NAT unchanged. NAT works on addresses and ports. It does not read or alter the encrypted content.</li><li><strong>What the provider observes.</strong> The source address is 203.0.113.10. The provider sees nothing of 10.0.11.25.</li><li><strong>Response.</strong> The provider answers to 203.0.113.10:1024. NAT finds the mapping for port 1024, rewrites the destination back to 10.0.11.25:51514 and delivers the packet.</li></ol><p>You can check this yourself. From the instance, run:</p><pre>curl https://checkip.amazonaws.com</pre><p>It prints the public address that the outside world sees. It should be the Elastic IP of the NAT gateway.</p><h3>Why providers use IP allow-listing</h3><h3>How a provider identifies connections</h3><p>All a server knows about a TCP connection is the address it came from. A provider that wants to restrict access can compare that address with a list before it does anything else. It is simple, cheap and it stops traffic from the rest of the internet early.</p><h3>Why domain names are not a substitute</h3><p>The provider’s server sees an IP address, not your domain name. Looking up the name behind an address (reverse DNS) is unreliable and anyone can set it for their own addresses. A provider cannot rely on it.</p><h3>IP allow-listing, API keys, OAuth and mTLS</h3><p>MethodWhat it provesIP allow-listThe call came from a network you namedAPI keyThe caller holds a shared secretOAuthA specific client was granted specific permissions, for a limited timemTLSThe caller holds a private key matching a certificate the provider trusts</p><h3>IP allow-listing alone is not authentication</h3><p>An address is a location, not an identity. Anything that can send traffic through your NAT gateway shares its address: every instance in those subnets, including a compromised one. A released-and-reassigned EIP gives the same address to someone else. Providers therefore combine the allow-list with a credential. Use both: the allow-list narrows where calls may come from, and a key, token or certificate shows who is calling.</p><h3>High availability with multiple AZs</h3><h3>One NAT gateway or one per AZ</h3><p>A single NAT gateway is cheaper and gives one address to register. But it lives in one zone, and every private subnet in the VPC uses it. If that zone has a problem, instances in the <em>other</em> zones keep running but lose outbound access, because their route still points to a NAT gateway that is not answering. The rest of the architecture survives the zone failure, and the integration does not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azFcXL-NjZeHlLSXSSqj8w.png" /></figure><p>The common design is <strong>one NAT gateway per AZ</strong>, each with its own Elastic IP, and each private subnet routed to the NAT gateway in the <em>same</em> zone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQibtshxUEVib3nJbAS1MQ.png" /></figure><h3>Different Elastic IPs, and the allow-list</h3><p>Two NAT gateways means two public addresses. A call can leave from either one, depending on which zone the instance is in. <strong>The provider must allow-list all of them.</strong> Register every address before go-live, not after the first failure. When you add a zone later, you have to ask the provider again, so plan for the number of zones you may use.</p><h3>When one NAT gateway or zone fails</h3><p>With one NAT gateway per zone, a failure stays in its zone. Instances in the healthy zone keep calling out through their own NAT gateway, from their own address. The instances in the failed zone are gone anyway, and replacements start in the healthy zone.</p><h3>Route table considerations</h3><p>Create one route table per private subnet (or per zone). Each sends 0.0.0.0/0 to the NAT gateway in its own zone. Staying in the zone also avoids cross-zone data transfer charges.</p><p>Route tableDestinationTargetpublic (both zones)10.0.0.0/16local0.0.0.0/0igw-0abc… (internet gateway)private-a10.0.0.0/16local0.0.0.0/0nat-0aaa… (NAT gateway in zone a)private-b10.0.0.0/16local0.0.0.0/0nat-0bbb… (NAT gateway in zone b)</p><p>With the AWS CLI, for zone a:</p><pre># 1. Allocate an Elastic IP<br>aws ec2 allocate-address --domain vpc</pre><pre># 2. Create the NAT gateway in the PUBLIC subnet of zone a<br>aws ec2 create-nat-gateway \<br>  --subnet-id subnet-0publica \<br>  --allocation-id eipalloc-0aaa \<br>  --connectivity-type public</pre><pre># 3. Send the private subnet&#39;s internet traffic to it<br>aws ec2 create-route \<br>  --route-table-id rtb-0privatea \<br>  --destination-cidr-block 0.0.0.0/0 \<br>  --nat-gateway-id nat-0aaa</pre><ul><li>allocate-address reserves the static public address for your account and returns its allocation ID (eipalloc-…).</li><li>create-nat-gateway takes the <em>public</em> subnet (the one routed to the internet gateway) and the EIP&#39;s allocation ID. --connectivity-type public is the default and is shown for clarity.</li><li>create-route adds the default route to the private route table. If the route exists and you want to change its target, use replace-route with the same arguments.</li></ul><p>Repeat with zone b’s subnets and a second EIP. Always create a NAT gateway only after its subnet has a route to the internet gateway, otherwise it cannot send traffic out.</p><p>Two more notes. A NAT gateway cannot have a security group, so control outbound traffic with the instances’ security groups and with network ACLs. And one NAT gateway has limits (for example, about 55,000 simultaneous connections to a single destination address and port). A very chatty service may need more than one address.</p><h3>NAT gateway versus forward proxy</h3><p>A NAT gateway changes the <strong>source address</strong> of packets. A forward proxy (the opposite of the reverse proxy from Article 1) is an application that makes requests <strong>on the client’s behalf</strong>. Same traffic, different layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LskRWFVJsS8862iCETM_ag.png" /></figure><p>NAT gatewayForward proxyFixed public IPYes, from its Elastic IPNot by itself; it uses whatever address its own egress path hasDomain filteringNo. It sees addresses and ports onlyYes: allow or deny by host nameAuthenticationNoYes: per client or per service credentialsLoggingConnection records through VPC Flow Logs (IPs and ports)Per-request logs with the requested host, status and callerCentral outbound policyOnly routing rulesOne place for rules and exceptionsHTTPSPasses it through, without looking insideUses the CONNECT method: the client asks the proxy to open a tunnel to host:443, so the proxy sees the host name but not the content (unless you deliberately intercept TLS)InfrastructureManaged by AWSYou run, patch, scale and monitor it</p><p><strong>The NAT gateway does not provide hostname allow-listing.</strong> It will carry a connection to any destination if the route and security groups allow it. If your policy is “this service may only call these two providers”, NAT alone does not enforce it.</p><h3>When is a forward proxy necessary?</h3><p>Two common choices are <strong>Squid</strong>, the long-established caching and filtering proxy, and <strong>Caddy</strong> with the forward_proxy plugin. The plugin is not in the standard Caddy build, so you add it with xcaddy (see Article 1).</p><h3>A proxy does not give you a fixed IP</h3><p>This is the point most often missed. A proxy is a program on a server. Its outbound traffic leaves with that server’s own address. If the proxy sits in a private subnet, its traffic still goes through the NAT gateway, and the Elastic IP is still what the provider sees. If it sits in a public subnet with its own Elastic IP, that is the address. Either way, <strong>the fixed address comes from the egress configuration, not from the proxy</strong>. A proxy placed on an instance with an ordinary changing public address would make things worse.</p><h3>Examples</h3><p>Squid, allowing only listed hosts, from our VPC only:</p><pre>acl vpc src 10.0.0.0/16<br>acl allowed_sites dstdomain .provider-a.example.com .provider-b.example.com<br>acl SSL_ports port 443<br>acl CONNECT method CONNECT</pre><pre>http_access allow vpc CONNECT SSL_ports allowed_sites<br>http_access allow vpc allowed_sites<br>http_access deny all</pre><pre>http_port 3128</pre><ul><li>acl vpc src … matches clients from the VPC range. acl allowed_sites dstdomain … matches destination host names, and the leading dot includes sub-domains.</li><li>The CONNECT rule lets HTTPS tunnels open only to port 443 on allowed hosts.</li><li>http_access deny all refuses everything not matched above. http_port 3128 is where Squid listens.</li></ul><p>Caddy with the plugin (xcaddy build --with github.com/caddyserver/forwardproxy):</p><pre>{<br>    order forward_proxy before file_server<br>}</pre><pre>:3128 {<br>    forward_proxy {<br>        basic_auth doc_service {env.PROXY_PASSWORD}<br>        acl {<br>            allow provider-a.example.com<br>            allow provider-b.example.com<br>            deny all<br>        }<br>    }<br>}</pre><ul><li>order forward_proxy before file_server places this non-standard directive in Caddy&#39;s directive order.</li><li>basic_auth requires the client to send credentials, here read from an environment variable.</li><li>acl allows the listed hosts and denies everything else.</li></ul><p>Check the plugin’s documentation for the syntax of your version before using it.</p><h3>When a NAT gateway alone is enough</h3><ul><li>The only requirement is a stable source address for an allow-list.</li><li>You trust the workloads in the subnet and do not need to limit which hosts they may call.</li><li>You are happy with connection-level logs from VPC Flow Logs.</li></ul><h3>When a forward proxy adds real value</h3><ul><li>A security or compliance rule says a service may reach only named external hosts.</li><li>You need per-request logs showing which service called which host.</li><li>Many services need one central place for outbound rules, with credentials per service.</li><li>You must send particular traffic through a particular egress, or add controls that NAT cannot.</li></ul><p>If you need hostname filtering but do not want to run a proxy, AWS Network Firewall can filter outbound traffic by domain as a managed service. It has its own cost and complexity, so compare it with the proxy.</p><p>The proxy is itself a service you must keep available. One proxy instance is a single point of failure, so run one per zone behind the same egress design as above.</p><h3>Advantages and disadvantages</h3><p>NAT gateway with Elastic IPAdding a forward proxyCostAn hourly charge per NAT gateway plus a charge per GB processed. AWS also charges for public IPv4 addresses. One gateway per zone multiplies the hourly cost. Traffic to S3 or DynamoDB can avoid NAT charges with gateway endpoints. Check current pricesAdds instances and their data transfer on top of NATAvailabilityManaged and redundant within a zone. Use one per zone to survive a zone failureYour responsibility: at least one per zone, health checks, replacementOperational complexityLow: create, route, forget. Remember the allow-list when adding zonesHigher: configuration, patching, scaling, certificate and credential handlingSecurityHides private addresses and blocks inbound connections. Does not limit destinationsAdds destination control, authentication and request logging. Becomes a sensitive component to protect</p><h3>Conclusion</h3><p>A private backend reaches the internet through a NAT gateway, which replaces the instance’s private address with the Elastic IP attached to it. That address belongs to your account, so it stays the same through deployments and instance replacements, and it is what a provider adds to its allow-list. Treat the Elastic IPs as long-lived assets: never release one that a provider still lists, and give providers every address you may use, including the one for each zone.</p><p>Choose the infrastructure from the requirement. If you only need a fixed source address, a NAT gateway per zone with its Elastic IP is enough. If you must also control which hosts a service can call, or record who called what, add a forward proxy or a managed firewall, and remember that it still leaves through the same NAT gateway. And since an allow-list is not authentication, keep an API key, OAuth token or client certificate in every provider integration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=049eeb9c4d53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Caddy on AWS: ALB, EC2, Availability Zones and high availability]]></title>
            <link>https://medium.com/@rameshkumarsgp/deploying-caddy-on-aws-alb-ec2-availability-zones-and-high-availability-1f1405376072?source=rss-c078d297bcc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f1405376072</guid>
            <category><![CDATA[caddy]]></category>
            <category><![CDATA[caddy-server]]></category>
            <dc:creator><![CDATA[Rameshkumar Shanmugam]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 06:28:15 GMT</pubDate>
            <atom:updated>2026-11-27T06:28:15.260Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3 of 3. Part 1 covered Caddy as a reverse proxy and Part 2 covered automatic HTTPS. This part puts a backend and Caddy on AWS and designs for failure.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dmv6JoUjqCkjndtOkopCyQ.png" /></figure><h3>Introduction</h3><p>A Caddyfile that works on your laptop is not a production system. In production something will fail: a process crashes, an instance is replaced, a data centre has a power problem. A single server answers requests until the moment it does not, and then the whole application is down.</p><p>Production design is about answering one question: <strong>what happens to users when a given part fails?</strong> This article builds an AWS architecture step by step. A backend application runs in Docker on EC2 instances, Caddy runs beside it, and an Application Load Balancer (ALB) receives the traffic. At each step we look at what fails and what keeps working.</p><p>One caution up front: <strong>deploying Caddy does not make an application highly available.</strong> Availability comes from running several instances in several Availability Zones behind a load balancer. Caddy is one component inside that design, and it is not the part that provides the redundancy.</p><h3>Understanding the deployment components</h3><ul><li><strong>Region.</strong> A geographic area, such as Mumbai (ap-south-1). Regions are independent of each other.</li><li><strong>Availability Zone (AZ).</strong> One or more separate data centres inside a Region, with their own power, cooling and networking. A Region has several AZs, connected with low-latency links. AZs are designed so that one can fail without taking the others with it.</li><li><strong>VPC.</strong> Your private virtual network inside a Region. It spans all the Region’s AZs and has an address range, for example 10.0.0.0/16.</li><li><strong>Subnets.</strong> A slice of the VPC that lives in exactly one AZ. A <strong>public subnet</strong> has a route to the internet gateway, so what is in it can be reached from the internet. A <strong>private subnet</strong> has no such route inbound, and is where application servers belong.</li><li><strong>EC2.</strong> Virtual machines. Each instance runs in one subnet, so in one AZ.</li><li><strong>Application Load Balancer.</strong> A managed layer-7 (HTTP) load balancer. It receives requests from the internet and spreads them over healthy targets.</li><li><strong>Security group.</strong> A virtual firewall attached to an instance or a load balancer. It lists which traffic is allowed in. It is stateful, so replies to allowed requests are allowed automatically.</li></ul><p><strong>Who manages what.</strong> AWS manages the ALB (its nodes, its scaling and its availability across AZs), the physical data centres and the network. You manage the instances, the operating system, Docker, Caddy, the application, the security group rules and how many instances you run and where.</p><h3>Where does Caddy fit into AWS?</h3><p>Compare two layouts.</p><ul><li><strong>Option A: Client → ALB → Backend application.</strong></li><li><strong>Option B: Client → ALB → Caddy → Backend application.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOLO7RjjrGQK9tw-SBJjNw.png" /></figure><p>The ALB is already a reverse proxy</p><p>An ALB terminates TLS, routes by host name and path, spreads requests across targets and removes unhealthy targets. These are the jobs Part 1 gave to Caddy. If the ALB’s routing is all you need, a second proxy repeats work and adds one more process to run, update and debug.</p><h3>When Caddy adds value</h3><ul><li><strong>Several containers on one instance.</strong> Caddy routes /api to one container and / to another, on the instance, with no extra target groups.</li><li><strong>Request and response changes</strong> the ALB cannot make: rewriting paths, adding or removing headers, compressing responses.</li><li><strong>Static files and application in one place</strong>, with Caddy serving the files directly.</li><li><strong>The same configuration everywhere.</strong> Local development, staging and production all run the same Caddyfile.</li><li><strong>Per-instance concerns</strong> such as local retries or access logs in a format you choose.</li></ul><h3>When Caddy is unnecessary</h3><ul><li>One application per instance, and routing is done by ALB rules.</li><li>You only need TLS and load balancing. The ALB does both.</li><li>Nobody on the team would own and monitor another moving part.</li></ul><p>The rule: <strong>add a proxy only when it has a clear responsibility of its own.</strong> The rest of this article uses Option B, because the Docker and Caddy questions are the subject here. If your case matches Option A, skip the Caddy container and point the ALB at the application.</p><h3>Deploying Caddy using Docker</h3><p>Each EC2 instance runs two containers: Caddy and the backend. Docker Compose defines both.</p><pre>services:<br>  caddy:<br>    image: caddy:2<br>    restart: unless-stopped<br>    ports:<br>      - &quot;80:80&quot;<br>    volumes:<br>      - ./Caddyfile:/etc/caddy/Caddyfile:ro<br>      - caddy_data:/data<br>      - caddy_config:/config<br>    depends_on:<br>      - backend</pre><pre>  backend:<br>    image: 123456789012.dkr.ecr.ap-south-1.amazonaws.com/orders-api:1.4.2<br>    restart: unless-stopped<br>    expose:<br>      - &quot;3000&quot;<br>    environment:<br>      PORT: &quot;3000&quot;</pre><pre>volumes:<br>  caddy_data:<br>  caddy_config:</pre><ul><li>caddy:2 is the official image, pinned to major version 2.</li><li>restart: unless-stopped restarts a container that crashes and after a reboot.</li><li>ports: &quot;80:80&quot; publishes only Caddy&#39;s port to the instance. The ALB reaches Caddy there.</li><li>The Caddyfile is mounted read-only (:ro) at the path Caddy reads.</li><li>/data and /config are the two directories Caddy writes to. caddy_data holds certificates and other state. caddy_config holds the last working configuration. Named volumes keep them when the container is replaced. Behind an ALB Caddy does not request public certificates, but it still keeps its state here.</li><li>expose: &quot;3000&quot; makes the backend reachable from other containers on the same network but <strong>not</strong> from outside the instance. There is no ports entry for it.</li></ul><h3>Container networking and service discovery</h3><p>Compose puts both services on one private network and gives each service a DNS name equal to its service name. Caddy can therefore reach the backend at backend:3000. No IP address is written anywhere, and it keeps working when the backend container is recreated.</p><h3>The Caddyfile</h3><pre>{<br>    auto_https off<br>    servers {<br>        trusted_proxies static 10.0.0.0/16<br>        metrics<br>    }<br>}</pre><pre>:80 {<br>    log {<br>        output stdout<br>        format json<br>    }</pre><pre>    encode zstd gzip</pre><pre>    handle /healthz {<br>        reverse_proxy backend:3000<br>    }</pre><pre>    handle {<br>        reverse_proxy backend:3000<br>    }<br>}</pre><ul><li>auto_https off: the ALB terminates TLS, so Caddy must not try to get certificates (see Part 2).</li><li>trusted_proxies static 10.0.0.0/16: the ALB adds the real client address to X-Forwarded-For. Caddy believes that header only when the request comes from a trusted address, and here that is the VPC range. Use your own VPC CIDR. Without this, the backend sees the ALB&#39;s address as the client.</li><li>metrics: turns on Prometheus-format metrics for the servers.</li><li>:80: listen on port 80 for any host name. The ALB forwards to this port.</li><li>log { output stdout, format json }: writes structured access logs to the container&#39;s standard output.</li><li>encode zstd gzip: compress responses.</li><li>handle /healthz { reverse_proxy ... }: the health check path is passed on to the application. This is deliberate. If Caddy answered 200 by itself, the ALB would show a healthy target even when the application behind it is dead.</li><li>The last handle proxies every other request. Here the two blocks do the same thing. In practice the second would hold your routing rules.</li></ul><h3>Logging and monitoring</h3><ul><li>Docker can send each container’s output to CloudWatch Logs with the awslogs log driver, or you can run the CloudWatch agent on the instance. JSON logs are easy to query there.</li><li>Caddy’s metrics are served by its admin endpoint, localhost:2019/metrics, which listens on the instance only. Scrape it with an agent running on the instance, and do not expose port 2019 outside it.</li><li>The ALB publishes its own metrics to CloudWatch (request count, 5xx errors, healthy host count). The healthy host count is the one to alarm on.</li></ul><h3>Understanding the ALB</h3><h3>Listeners</h3><p>A listener checks for connection requests on a port and protocol and applies rules. A typical ALB has two: HTTPS on 443 and HTTP on 80.</p><h3>Target groups</h3><p>A target group is the list of destinations (here EC2 instances and a port) that receive requests. A listener rule forwards matching requests to a target group. Rules can match on host name or path, so one ALB can front several applications, each with its own target group.</p><h3>Health checks</h3><p>The ALB requests a path on each target regularly. A target that fails enough checks in a row is marked unhealthy and receives no requests until it passes again. Settings to know:</p><ul><li>the <strong>path</strong> (for example /healthz) and the expected status code;</li><li>the <strong>interval</strong> and <strong>timeout</strong> of each check;</li><li>the <strong>healthy and unhealthy thresholds</strong>: how many consecutive passes or failures change the state. The defaults for an ALB are 30 seconds, 5 seconds, 5 and 2, so detecting a dead target can take about a minute. Tune them to the speed you need.</li></ul><p>A good health endpoint checks what the application needs to serve a request (for example, that it can reach its database) and returns quickly.</p><h3>TLS termination with AWS Certificate Manager</h3><p>The ALB’s HTTPS listener holds a certificate from <strong>AWS Certificate Manager (ACM)</strong>. Public certificates from ACM are free when used with an ALB, and ACM renews them for you. This is the same idea as Part 2, with AWS as the certificate manager instead of Caddy. Requests are decrypted at the ALB and sent to targets. A target group can use HTTP, which is common inside a VPC, or HTTPS if you want the last hop encrypted too.</p><h3>HTTP to HTTPS redirection</h3><p>Add a rule on the port 80 listener whose action is “redirect” to HTTPS on port 443 with status 301. The ALB does it, so Caddy needs nothing.</p><h3>Security group relationships</h3><ul><li><strong>ALB security group:</strong> inbound 80 and 443 from the internet (0.0.0.0/0).</li><li><strong>Instance security group:</strong> inbound port 80 <strong>only from the ALB security group</strong>. The source is the group itself, not an IP range, so it keeps working as the ALB’s nodes change.</li></ul><h3>Multiple EC2 instances</h3><h3>One instance is a single point of failure</h3><p>With one instance, an operating system crash, a failed deployment, a full disk or a reboot for patching all cause downtime. The ALB cannot help, because it has nowhere else to send requests.</p><p>[Insert Figure 2: Single AZ, one instance]</p><h3>Deploying several instances</h3><p>Run two or more identical instances, each with the same Compose file. Register them all in the same target group. Create them from one machine image or launch template. An <strong>Auto Scaling group</strong> is the usual way: it keeps a set number of instances running, replaces any that fail, and can add more when load rises. Turn on its ELB health check type so that an instance the ALB sees as unhealthy is replaced, not just left out of rotation.</p><h3>Distributing requests and health-based routing</h3><p>The ALB sends each new request to one of the healthy targets, by default in round-robin order (a “least outstanding requests” algorithm is available). When one instance fails its health checks, the ALB stops sending to it while the others keep answering, so users see no error beyond the few requests in flight. When the instance recovers, it takes traffic again.</p><p>Two practical points. The application should be <strong>stateless</strong>, or keep its state outside the instance (a database, a cache), because consecutive requests from one user may reach different instances. And deregistering an instance gives in-flight requests time to finish (the deregistration delay, 300 seconds by default).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZy5BsD9EhGP8PXmroBGVw.png" /></figure><h3>Multiple Availability Zones</h3><h3>One AZ versus many</h3><p>Several instances in one AZ protect against an instance failure. They share the AZ, so they also share its failure modes: a power or network problem there takes all of them. Spreading instances over at least two AZs removes that shared fate.</p><h3>The ALB across AZs</h3><p>An ALB is always created with subnets in at least two AZs, and AWS places load balancer nodes in each. Put an instance subnet in each of those zones and let the Auto Scaling group spread instances across them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugk2M_gO-Y23X2uHoqHFwA.png" /></figure><h3>Cross-zone load balancing</h3><p>Cross-zone load balancing lets every ALB node send requests to targets in any AZ. With an ALB it is on by default at the load balancer level. The effect: if one AZ has two instances and the other has four, requests still spread evenly over the six instances, and not half-and-half between zones. Without it, the two-instance zone would carry half the load.</p><h3>What happens when an AZ becomes unavailable?</h3><p>The targets in that AZ fail their health checks. The ALB stops routing to them, and traffic goes to the instances in the other AZ. Users see a short blip from requests that were in flight or were routed before the health checks failed, then service continues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1L9znJ-OkvcQ7YVpxrc8w.png" /></figure><p>This only works if the surviving zone can carry the whole load. If each of two zones normally runs at 70% of capacity, losing one overloads the other. Size for the loss of a zone, or let the Auto Scaling group launch replacements in the remaining zone quickly. And everything else in the path must be multi-AZ too: a database with one instance in the failed zone is still a single point of failure.</p><h3>What if the ALB goes down?</h3><p>There are three different failures. Keep them apart:</p><ul><li><strong>An individual ALB node fails.</strong> The ALB runs several nodes in each AZ it uses. AWS detects the failure, removes the node’s address from the DNS answers for the ALB name, and replaces the node. Clients retry and are given another address. This is routine for AWS, and you do nothing.</li><li><strong>An AZ fails.</strong> The ALB nodes in that zone are lost, along with the targets there. The nodes in the other zones keep working, and traffic continues from them. This is the situation in the figure above.</li><li><strong>A regional outage of the ALB service.</strong> This is rare, and it would affect every AZ in the Region at once. Multiple AZs do not protect you here, and only a second Region does (the next section).</li></ul><p>The ALB is a managed, multi-AZ service. AWS is responsible for its availability inside a Region. That is why <strong>a second ALB in the same Region is not the normal answer</strong>. It sits on the same regional service, so it does not remove the dependency that matters, and it adds more to pay for, configure and keep in step. There are good reasons to have more than one ALB (separating internal and public traffic, different security needs, different teams), but “more redundancy” is not one of them.</p><p>And again: a Caddy container on each instance does not make the ALB more available. It is behind the ALB, not beside it.</p><h3>Multi-region architecture</h3><h3>Why multiple AZs are not enough</h3><p>All AZs of a Region share one regional control plane, regional services and, to a degree, the same configuration and software releases. A problem at that level, or a Region-wide event, affects them all. If your business cannot tolerate that, you need a second Region.</p><h3>Two Regions</h3><p>Build the same stack in a second Region: its own VPC, ALB, instances and, as before, several AZs. Two patterns exist:</p><ul><li><strong>Active-passive.</strong> The second Region is kept ready but receives no traffic until the first fails. It costs less, and failover takes longer.</li><li><strong>Active-active.</strong> Both Regions serve users. Failover is faster, because the second Region is already running traffic, but the data problem is much harder.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXBuexa37OpqakKV_-dJnA.png" /></figure><h3>DNS routing and health checks</h3><p>Users need to be sent to whichever Region is healthy. Amazon Route 53 can do this with health checks and a routing policy: <em>failover</em> (primary, then secondary), <em>latency</em> (the nearest Region) or <em>weighted</em>. The health check should test a real path through the ALB. DNS answers are cached for the record’s TTL, so a short TTL makes failover quicker, but some clients will take longer to switch anyway.</p><h3>Database replication and consistency</h3><p>The hard part is the data. Stateless servers are easy to copy, but the database must exist in both Regions. Typical options are a primary database with a cross-Region read replica, or a managed global database, such as Aurora Global Database or DynamoDB global tables. Replication between Regions takes time, so after a failover the second Region may be missing the last writes. With writes in both Regions at once, conflicting updates must be resolved. These are application design questions, not infrastructure switches.</p><h3>RTO and RPO</h3><ul><li><strong>RTO</strong> (recovery time objective): how long the service may be down. It includes detecting the failure, DNS switching and promoting the database.</li><li><strong>RPO</strong> (recovery point objective): how much recent data you may lose, which depends on replication lag.</li></ul><p>Decide both numbers from the business impact first, then pick the architecture that meets them.</p><h3>Complexity and cost</h3><p>A second Region roughly doubles the infrastructure bill and adds data transfer between Regions. It also adds the work of keeping both stacks identical, testing failover and deciding who may trigger it. A failover that has never been practised often fails when it is needed. For many applications, multiple AZs in one Region are enough. Choose multi-region deliberately, not by default.</p><h3>Security considerations</h3><ul><li><strong>ALB security group.</strong> Inbound 80 and 443 from the internet and nothing else. Outbound only to the instance security group.</li><li><strong>EC2 security group.</strong> Inbound only on the port Caddy listens on, and only from the ALB security group. If the application is reachable directly from the internet, the ALB’s protections can be bypassed. Place instances in private subnets so that they have no public address.</li><li><strong>Only the right caller.</strong> With Caddy in front of the application, the backend port is not published at all (expose, not ports), so only Caddy can reach it. Caddy is then the &quot;appropriate internal proxy&quot;.</li><li><strong>Administrative access.</strong> Do not open SSH (port 22) to the internet. Use AWS Systems Manager Session Manager, which needs no inbound port and gives an audit trail, or restrict SSH to a bastion or a fixed address range. Give the instance role only the permissions the instance needs, such as pulling images from ECR and writing logs.</li><li><strong>Admin endpoints.</strong> Keep Caddy’s admin API on localhost:2019, and do not publish it.</li><li><strong>TLS and internal encryption.</strong> TLS ends at the ALB with an ACM certificate (Part 2 explains termination). Traffic from the ALB to the instances then travels inside your VPC. For most applications HTTP is acceptable there. If your rules require encryption in transit everywhere, make the target group use HTTPS and give Caddy a certificate for that hop. The ALB does not verify the target’s certificate, so the certificate can come from Caddy’s internal CA.</li></ul><p>Instances in private subnets still need a way to reach the internet for tasks such as pulling container images or OS updates. How outbound traffic works, and how to give it a fixed address, is the subject of Article 4.</p><h3>Advantages and trade-offs</h3><p>BenefitTrade-offAvailabilitySurvives instance and AZ failures with no manual stepNeeds enough spare capacity and a stateless application; a region outage is not coveredScalabilityAdd instances behind the ALB, or let an Auto Scaling group do itScale-out is only as good as the application’s shared state (database, cache)Operational complexityAWS runs the ALB; Caddy config is short and the same in every environmentMore parts: subnets, security groups, target groups, scaling rules, deploymentsCostYou pay for what runs, and instances can scale downThe ALB has an hourly and a usage charge; redundant instances cost money even when idle; a second Region roughly doubles the bill</p><h3>Conclusion</h3><p>A reliable AWS deployment is built from layers, and each layer answers one failure. An ALB hides which instance is serving. Several instances survive an instance failure. Several AZs survive a zone failure. A second Region is the answer to a regional failure, and it comes with a data and cost problem of its own.</p><p>Caddy has a modest place in this picture. It is useful beside the application for routing, headers, compression and a configuration that matches your laptop, and it should earn its place with a job the ALB does not do. It does not provide availability on its own. If you remember one thing from this series, remember to ask, for every component: what happens when this fails?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f1405376072" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caddy automatic HTTPS: how TLS certificates and Let’s Encrypt work]]></title>
            <link>https://medium.com/@rameshkumarsgp/caddy-automatic-https-how-tls-certificates-and-lets-encrypt-work-807c9b99d75a?source=rss-c078d297bcc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/807c9b99d75a</guid>
            <category><![CDATA[caddy-server]]></category>
            <category><![CDATA[caddy]]></category>
            <dc:creator><![CDATA[Rameshkumar Shanmugam]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 06:08:50 GMT</pubDate>
            <atom:updated>2026-11-27T06:08:50.531Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of 3. Part 1 covered Caddy as a web server and reverse proxy. This part explains what Caddy does to get and keep HTTPS working. Part 3 covers production deployment.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgRcsErYwZDyQEkAiPywyw.png" /></figure><h3>Introduction</h3><p>In Part 1 the examples used :8080 and http:// addresses on purpose. That kept HTTPS out of the picture. Replace that address with a real domain name, and Caddy serves your site over HTTPS without another line of configuration:</p><pre>example.com {<br>    reverse_proxy localhost:3000<br>}</pre><p>This article answers one question: <strong>why is that enough, and what is Caddy doing behind the scenes?</strong></p><p>Plain HTTP is not enough for a production site, for three reasons. Anyone on the network path (a shared Wi-Fi, an internet provider, a compromised router) can read HTTP traffic, including passwords and session cookies. They can also change it in transit. And the browser has no way to know that the server it reached is really the one named in the address bar. HTTPS fixes all three. Browsers now mark HTTP pages as “Not secure”, and many browser features (geolocation, service workers, some APIs) only work over HTTPS. HTTPS needs TLS, and TLS needs a certificate that browsers trust. Getting and renewing that certificate used to be a manual job. Caddy does it for you.</p><h3>Understanding HTTPS and TLS</h3><h3>HTTP versus HTTPS</h3><p>HTTPS is ordinary HTTP carried inside a TLS connection. The requests and responses are the same. The difference is that TLS wraps them first. HTTP uses port 80 by default and HTTPS uses port 443.</p><h3>What TLS provides</h3><ul><li><strong>Encryption.</strong> Only the two ends can read the traffic.</li><li><strong>Integrity.</strong> Any change in transit is detected, so the data cannot be quietly altered.</li><li><strong>Authentication.</strong> The server proves that it is the owner of the domain name the user asked for.</li></ul><h3>Public and private keys</h3><p>TLS uses a key pair. The <strong>private key</strong> stays on the server and is never shared. The <strong>public key</strong> is given to everyone. Something signed with the private key can be checked with the public key, but only the owner of the private key could have signed it. That is how a server proves its identity. The bulk of the traffic is not encrypted with this pair. It uses a faster symmetric session key that the two sides agree on during the handshake.</p><h3>The TLS handshake</h3><p>Before any HTTP is sent, the browser and server run a handshake. In TLS 1.3, the current version, it takes one round trip:</p><ol><li><strong>ClientHello.</strong> The browser sends the TLS versions and cipher suites it supports, the host name it wants (the server name indication, or SNI) and its half of a key agreement.</li><li><strong>ServerHello.</strong> The server picks a cipher suite and sends its half of the key agreement. Both sides can now work out the same session keys. Everything after this is encrypted.</li><li><strong>Certificate.</strong> The server sends its certificate chain and a signature made with its private key, proving that it owns the certificate.</li><li><strong>Verification.</strong> The browser checks the certificate (see the next section) and both sides send “Finished”.</li><li><strong>Application data.</strong> The HTTP request and response now travel encrypted.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mszHZLA22tZQGHlMXHSyVQ.png" /></figure><p>The SNI matters for Caddy. One Caddy server can hold many certificates, and the host name in the ClientHello tells it which one to present.</p><h3>What a certificate contains</h3><ul><li>The <strong>subject</strong> and the <strong>subject alternative names</strong> (SANs): the domain names the certificate is valid for.</li><li>The server’s <strong>public key</strong>.</li><li>The <strong>issuer</strong>: the certificate authority that signed it.</li><li>The <strong>validity period</strong>: when it starts and when it expires.</li><li>The issuer’s <strong>signature</strong> over all of the above.</li></ul><h3>Understanding certificate authorities</h3><p>A <strong>certificate authority</strong> (CA) is an organisation that checks that someone controls a domain and then signs a certificate saying so. A certificate is only worth something because the browser trusts whoever signed it.</p><h3>How browsers trust certificates</h3><p>Browsers and operating systems ship with a list of <strong>root certificates</strong>, the trust store. A root CA is trusted because it is in that list, and a certificate is trusted if it can be traced back to one of those roots.</p><h3>Root and intermediate certificates</h3><p>Root CAs rarely sign website certificates directly, because their private keys are kept offline and are very valuable. A root signs one or more <strong>intermediate</strong> certificates, and those intermediates sign the website’s <strong>leaf</strong> certificate. The server sends the leaf and the intermediates. The root is already in the browser.</p><h3>Chain validation</h3><p>The browser walks up the chain from the leaf and checks that:</p><ol><li>each certificate’s signature was made by the one above it;</li><li>every certificate is within its validity dates;</li><li>the leaf lists the host name the user asked for;</li><li>the chain ends at a root in the trust store.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GudTsntsuBwsOCUPHZkgA.png" /></figure><p>When a certificate is invalid or expired</p><p>A browser shows a full-page warning (for example, “Your connection is not private” with NET::ERR_CERT_DATE_INVALID), and most visitors turn back. Programs are stricter. An API client, a mobile app or curl simply fails the request with a certificate error. An expired certificate is one of the most common causes of an outage, and it is entirely avoidable.</p><h3>What is Let’s Encrypt?</h3><p><strong>Let’s Encrypt</strong> is a certificate authority that is free, automated and trusted by all major browsers. It is run by a non-profit, the Internet Security Research Group. Before it existed, certificates cost money and needed manual paperwork. Let’s Encrypt made them free and scriptable.</p><h3>The ACME protocol</h3><p><strong>ACME</strong> (Automatic Certificate Management Environment) is the standard protocol that lets software ask a CA for a certificate with no human involved. Let’s Encrypt is one CA that speaks ACME. Others do too, and Caddy works with any of them.</p><h3>Domain ownership validation</h3><p>Before signing, the CA must be sure the requester controls the domain. It sets a <strong>challenge</strong>: do something only the domain’s owner could do. The two common challenges:</p><ul><li><strong>HTTP-01.</strong> The CA gives the client a token, and the client publishes it at http://example.com/.well-known/acme-challenge/&lt;token&gt;. The CA fetches it from the outside, over port 80. It proves control of the web server at that name.</li><li><strong>DNS-01.</strong> The client creates a DNS TXT record at _acme-challenge.example.com. The CA looks the record up. It proves control of the DNS zone. It needs no open ports, and it is the only challenge that can issue <strong>wildcard</strong> certificates (*.example.com).</li></ul><p>There is a third, <strong>TLS-ALPN-01</strong>, which answers the challenge during a TLS handshake on port 443. Caddy uses it too.</p><h3>Issuance and renewal</h3><p>Let’s Encrypt certificates are short-lived on purpose (90 days at the time of writing, with the CA moving towards even shorter lifetimes). Short lifetimes limit the damage from a stolen key and force automation. The software renews well before the end, so renewal is part of normal operation, not an emergency.</p><h3>How Caddy automates HTTPS</h3><p>Here is the whole lifecycle, from a domain in the config to a renewed certificate.</p><ol><li><strong>A domain is configured.</strong> You write example.com { ... } as the site address.</li><li><strong>Caddy decides HTTPS is needed.</strong> A site address that is a public host name, without an http:// prefix, makes Caddy treat it as a site to secure. It listens on port 443 and also on port 80 to redirect to HTTPS.</li><li><strong>Caddy contacts an ACME CA.</strong> It registers an account and opens an order for the name. By default it uses Let’s Encrypt and ZeroSSL.</li><li><strong>Domain ownership is validated.</strong> Caddy answers the challenge itself: HTTP-01 on port 80 or TLS-ALPN-01 on port 443. The CA connects from the outside and checks.</li><li><strong>A certificate is issued.</strong> Caddy generates a new private key and sends a certificate signing request (CSR). The CA signs it and returns the certificate.</li><li><strong>Caddy stores and serves it.</strong> The certificate and key are written to Caddy’s data directory and loaded into memory. The handshake from the first section now uses it, chosen by SNI.</li><li><strong>Caddy renews it.</strong> A background job checks the certificates and renews each one when roughly a third of its lifetime is left, with no restart and no downtime.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLewswyVKWO6AE2NWi_MAQ.png" /></figure><p>What you no longer do by hand</p><ul><li>Generate a private key and a CSR.</li><li>Run a client, publish the challenge token or edit DNS.</li><li>Install the certificate and the intermediate chain in the right files.</li><li>Schedule renewal and reload the server afterwards.</li><li>Redirect HTTP to HTTPS.</li></ul><p>Caddy also uses sensible TLS defaults: modern protocol versions and cipher suites with no tuning from you.</p><h3>What you still must provide</h3><p>The automation works only if the outside world can reach Caddy. Check these first, because they cause most first-time failures:</p><ul><li><strong>DNS.</strong> The domain’s A (and AAAA, if you publish one) record must point to the server. If an AAAA record points somewhere else, the CA may validate against that address and fail.</li><li><strong>Firewall.</strong> Port 80 and port 443 must be open from the internet. Port 80 is needed for HTTP-01 and the redirect, port 443 for TLS-ALPN-01 and for serving. This applies to cloud security groups and host firewalls too.</li><li><strong>A public name.</strong> A public CA cannot issue for localhost, a private IP or an internal-only name.</li><li><strong>Persistent storage.</strong> Caddy’s data directory must survive restarts. In a container that means a mounted volume. If Caddy loses its certificates it asks for new ones every time, and the CA’s rate limits will block you.</li></ul><h3>Caddy configuration examples</h3><h3>Automatic HTTPS with a domain</h3><pre>example.com {<br>    reverse_proxy localhost:3000<br>}</pre><ul><li>example.com is a public host name with no scheme or port, so Caddy serves it over HTTPS and obtains the certificate.</li><li>reverse_proxy localhost:3000 is the same directive as in Part 1. TLS is handled before this line runs.</li></ul><p>An optional global block sets an email address that the CA can use for expiry notices and account recovery:</p><pre>{<br>    email admin@example.com<br>}</pre><pre>example.com {<br>    reverse_proxy localhost:3000<br>}</pre><p>A block with no address in braces at the top of the file holds global options. email is the contact address for the ACME account.</p><h3>HTTP to HTTPS redirection</h3><p>Caddy sends HTTP requests to HTTPS by default, so you write nothing. To redirect another name, such as the www host, to the main site, use redir:</p><pre>www.example.com {<br>    redir https://example.com{uri} permanent<br>}</pre><pre>example.com {<br>    reverse_proxy localhost:3000<br>}</pre><ul><li>redir answers with a redirect to the target.</li><li>{uri} is a placeholder that keeps the path and query string.</li><li>permanent uses status 301 instead of the default 302.</li></ul><p>If you ever need to change the default, the global option auto_https takes off, disable_redirects or disable_certs.</p><h3>Custom certificate</h3><p>If your organisation issues its own certificates, point Caddy at the files. Caddy then does not request one for this site.</p><pre>example.com {<br>    tls /etc/caddy/certs/example.com.crt /etc/caddy/certs/example.com.key<br>    reverse_proxy localhost:3000<br>}</pre><ul><li>tls with two arguments loads a certificate file (include the intermediates in it) and its private key.</li></ul><p>Renewing a manual certificate is back to being your job.</p><h3>DNS challenge</h3><p>Use the DNS challenge for wildcard certificates, or when the server cannot be reached from the internet on ports 80 and 443. It needs a <strong>DNS provider plugin</strong>, which is not in the standard Caddy build. You compile it in with xcaddy, for example:</p><pre>xcaddy build --with github.com/caddy-dns/cloudflare</pre><pre>*.example.com {<br>    tls {<br>        dns cloudflare {env.CLOUDFLARE_API_TOKEN}<br>    }</pre><pre>    @app host app.example.com<br>    handle @app {<br>        reverse_proxy localhost:3000<br>    }</pre><pre>    handle {<br>        respond &quot;Not found&quot; 404<br>    }<br>}</pre><ul><li>*.example.com asks for a wildcard certificate, which only the DNS challenge can give.</li><li>dns cloudflare {env.CLOUDFLARE_API_TOKEN} selects the DNS provider module and reads its API token from an environment variable, so the secret stays out of the file.</li><li>@app host app.example.com defines a named matcher that selects one host name.</li><li>handle @app { ... } runs the proxy only for that host. The last handle answers everything else.</li></ul><p>Requirements: the plugin for your DNS provider, an API token that can edit TXT records in that zone, and a DNS zone you actually control. Ports 80 and 443 do not need to be open for the issuance itself.</p><h3>Caddy and alternative certificate authorities</h3><p>CAWhat it isWhen it is appropriate<strong>Let’s Encrypt</strong>Free, public, trusted by browsersThe default for public sites<strong>ZeroSSL</strong>A second public ACME CA, free tierAs a fallback. Caddy uses both by default, so if one is down or rate limiting you the other can issue<strong>A custom ACME CA</strong>Any ACME server, for example one run inside a company or a paid CA with ACME supportWhen the organisation requires a specific CA, or needs extended validation or support terms<strong>Caddy’s internal CA</strong>A private CA built into CaddyDevelopment and internal services that are not on the public internet</p><p>Choosing a specific ACME CA, including a staging one for testing, is a global option:</p><pre>{<br>    email admin@example.com<br>    acme_ca https://acme-staging-v02.api.letsencrypt.org/directory<br>}</pre><ul><li>acme_ca sets the ACME directory URL. The staging URL issues certificates that browsers do not trust. It has far looser rate limits, so use it while you are testing a new setup.</li></ul><h3>Public CA versus internal CA</h3><ul><li><strong>Publicly trusted certificates</strong> (Let’s Encrypt, ZeroSSL) work in every browser with no setup on the visitor’s side, because the roots are already in the trust store. They require a public domain.</li><li><strong>Self-signed certificates</strong> are signed by themselves, with no CA above them. Nobody trusts them by default, so every visitor gets a warning unless you install the certificate on every client one by one.</li><li><strong>Caddy’s internal CA</strong> is a better version of self-signed. Caddy creates its own root and intermediate and issues leaf certificates automatically, and renews them. It is just as private, though: the root is not in anyone’s trust store.</li></ul><pre>app.internal.test {<br>    tls internal<br>    reverse_proxy localhost:3000<br>}</pre><ul><li>tls internal tells Caddy to use its own CA instead of a public one, so no outside server is contacted.</li></ul><h3>Why clients must trust the root</h3><p>Remember how validation works: the chain must end at a root the browser already trusts. Caddy’s root is not on that list. Until a client installs it, the chain ends at an unknown root and the browser shows a warning. On your own machine, caddy trust installs the root into the local trust store. For other devices you distribute the root certificate (it lives in Caddy&#39;s data directory under pki/authorities/local) yourself, for example through device management.</p><h3>Development versus production</h3><ul><li><strong>Development and internal tools:</strong> the internal CA. You get HTTPS locally that behaves like production, and you control who trusts the root.</li><li><strong>Public production sites:</strong> a public CA, because you cannot ask every visitor to install your root.</li><li><strong>Private internal systems</strong> where you run all the clients: the internal CA is a reasonable choice, provided the root is distributed.</li></ul><h3>Caddy versus managing Let’s Encrypt by hand</h3><p>Caddy does not replace Let’s Encrypt or any other CA. It is an ACME client, and the CA still checks the domain and signs the certificate. What changes is who does the work. The common manual tool is Certbot, and a hand-managed setup behaves differently from Caddy in these ways:</p><p>Manual (for example Certbot + a web server)CaddyIssuanceRun the client, pick a challenge method, point it at the web root or pluginAutomatic when a site address is a public nameRenewalA scheduled job (cron or a systemd timer) that you set up and monitorBuilt in and runs inside the serverConfigurationCertificate paths and TLS settings written in the server configNone; paths and TLS defaults are managed for youOperational overheadTwo systems to keep in step: the client and the serverOne processFailure handlingIf the job fails silently, the certificate expires. You need monitoringRetries with backoff, keeps serving the current certificate until it expires, and can fall back to a second CA</p><p>Caddy does not make failure impossible. A closed port, a wrong DNS record or a lost data directory will still stop issuance, so you should still monitor expiry.</p><h3>TLS termination</h3><p><strong>TLS termination</strong> is the point where the encrypted connection ends and the traffic becomes plain HTTP again. It is a different thing from certificate issuance. Issuance is how a certificate is obtained. Termination is where it is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v39ZVe6DNR0MC8bbI9I03w.png" /></figure><p>Termination at Caddy</p><p>The browser’s HTTPS connection ends at Caddy. Caddy holds the certificate and key, and forwards plain HTTP to the backend. This is the simplest layout and the one the earlier examples use.</p><h3>Termination at a cloud load balancer</h3><p>Some platforms put a load balancer in front, and it holds the certificate. Caddy then receives traffic that has already been decrypted, or re-encrypted with a different certificate. Because the public certificate is not Caddy’s job, you do not want Caddy to request one. Use an http:// address so that it serves plain HTTP behind the load balancer:</p><pre>http://example.com {<br>    reverse_proxy localhost:3000<br>}</pre><p>The details of a specific cloud deployment are the subject of Part 3.</p><h3>TLS between the proxy and the backend</h3><p>Caddy can encrypt the last hop as well, by giving the upstream an https:// address:</p><pre>example.com {<br>    reverse_proxy https://backend.internal:8443<br>}</pre><p>Caddy verifies the backend’s certificate, so that backend needs one issued by a CA that Caddy trusts (an internal CA works). Switching off that verification is possible, but it removes the protection and should not be done outside a test.</p><h3>When internal traffic should use HTTPS</h3><ul><li><strong>Same machine</strong> (localhost): plain HTTP is normally fine. The traffic never leaves the host.</li><li><strong>Across a network you do not fully control</strong>, such as between hosts, between data centres or over a shared network: use HTTPS.</li><li><strong>Regulated data</strong> or compliance rules that require encryption in transit everywhere: use HTTPS on every hop.</li><li><strong>A private network with strict controls:</strong> plain HTTP can be an accepted trade-off. It is a risk decision, not a technical limit.</li></ul><h3>Advantages and limitations</h3><h3>Advantages</h3><ul><li>HTTPS with no certificate work: issue, install, renew and redirect are all handled.</li><li>Fewer outages from expired certificates.</li><li>Free public certificates, with a second CA as a fallback.</li><li>The same configuration style works for public sites and for an internal CA.</li><li>Modern TLS defaults, with no tuning.</li></ul><h3>Limitations and things to watch</h3><ul><li>Automation depends on DNS, open ports and a persistent data directory. When they are wrong, issuance fails and the error appears in Caddy’s logs.</li><li>CA rate limits apply. Use a staging CA while testing, and keep the data directory so that certificates are not re-requested.</li><li>Wildcards and servers that are not reachable from the internet need a DNS plugin and a custom build.</li><li>Several Caddy servers behind one name need to share certificate storage so they do not each request their own. That belongs to the high-availability discussion in Part 3.</li><li>Caddy does not set an HSTS header for you. Add one yourself, and only when you are sure HTTPS will stay on.</li><li>You still need to monitor certificate expiry as a safety net.</li></ul><h3>Conclusion</h3><p>Caddy makes HTTPS simple because it takes on the work around certificates. When a site address is a public domain, it speaks ACME to a certificate authority, proves control of the domain with a challenge, stores the signed certificate, serves it during every TLS handshake and renews it before it expires. The CA still does the trusting. Caddy does the paperwork.</p><p>With the examples above you can enable HTTPS for a domain, redirect other names, load your own certificate, use the DNS challenge for wildcards, switch to another CA or an internal one, and decide where TLS should end. Part 3 puts all of this into a production deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=807c9b99d75a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caddy: a modern web server and reverse proxy, and how it works]]></title>
            <link>https://medium.com/@rameshkumarsgp/caddy-a-modern-web-server-and-reverse-proxy-and-how-it-works-b444d78145dd?source=rss-c078d297bcc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b444d78145dd</guid>
            <category><![CDATA[caddy]]></category>
            <category><![CDATA[caddy-server]]></category>
            <dc:creator><![CDATA[Rameshkumar Shanmugam]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 05:56:20 GMT</pubDate>
            <atom:updated>2026-11-27T05:56:20.623Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1 of 3. This part covers what Caddy does and how to configure it. HTTPS automation is Part 2 and production deployment is Part 3.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*siTCDEXnUybpd3LKWZOqZA.png" /></figure><p>Introduction</p><p>A web server answers HTTP requests. A browser asks for /index.html, and the server finds the file and sends it back. That was the whole job in the early web. Today most of what a server does is not serving files. It sits in front of applications written in Node, Go, Python or Java, and decides which one should handle each request.</p><p>That is the job of a <strong>reverse proxy</strong>. A normal (forward) proxy sits in front of clients and hides them from the internet. A reverse proxy sits in front of servers and hides them from clients. Clients talk to one address, and the proxy forwards each request to the right backend.</p><p>Teams put a reverse proxy in front of their applications for four reasons:</p><ul><li><strong>One public entry point.</strong> Many applications, one address and port.</li><li><strong>Routing.</strong> /api goes to one service and / goes to another.</li><li><strong>Load balancing.</strong> Traffic is spread over several copies of an application.</li><li><strong>Shared concerns.</strong> Compression, logging and access control live in one place, not in every application.</li></ul><p>Caddy is a web server and reverse proxy that does all of this from a short configuration file. This article explains how it works, how to write its configuration, and where it fits next to Nginx and Apache.</p><h3>What is Caddy?</h3><p>Caddy is an open-source web server written in Go. It ships as a single binary with no runtime dependencies. You download it, write a config file and run it.</p><h3>Caddy as a web server</h3><p>Caddy can serve static files (HTML, CSS, JavaScript, images) straight from disk using the file_server directive. It also compresses responses, writes access logs and can render simple templates.</p><h3>Caddy as a reverse proxy</h3><p>With the reverse_proxy directive, Caddy accepts a request and sends it to one or more backend applications. It copies the response back to the client. Caddy supports HTTP/1.1, HTTP/2 and HTTP/3 on the client side, WebSockets, and streaming responses.</p><h3>Static files versus proxying</h3><p>Serving static files means Caddy itself reads a file and answers. Proxying means Caddy does not produce the content. It passes the request to another process, waits for the answer and relays it. A single Caddy site can do both, using different paths.</p><h3>Architecture in brief</h3><ul><li><strong>Modules.</strong> Almost everything is a module: the file server, the reverse proxy, compression, logging. The core only loads and runs modules.</li><li><strong>JSON is the native configuration.</strong> The Caddyfile is a friendly format that Caddy converts (adapts) to JSON when it starts.</li><li><strong>Admin API.</strong> By default Caddy listens on localhost:2019 so its configuration can be read and changed at runtime, and reloaded without dropping connections.</li><li><strong>Built-in features versus plugins.</strong> The standard build includes the file server, reverse proxy, load balancing, health checks, compression, logging, redirects and basic authentication. Extra modules (for example rate limiting or a layer-4 TCP/UDP proxy) are plugins that you compile in with the xcaddy tool.</li></ul><h3>How Caddy works</h3><p>Every request follows the same path:</p><p><strong>Client → Caddy → backend application → Caddy → client.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ps-zpbaneguSCwbRlYE4Q.png" /></figure><p>[Insert Figure 1: Request lifecycle]</p><ol><li><strong>Listening.</strong> Caddy opens the ports named in your site addresses, such as :8080. Several sites can share one port.</li><li><strong>Host-based routing.</strong> Caddy reads the Host header and chooses the site block that matches. app.example.com and admin.example.com can reach different backends through the same port.</li><li><strong>Path-based routing.</strong> Inside a site, matchers look at the request path. /api/* can go to an API while everything else goes to a frontend.</li><li><strong>Request forwarding.</strong> For the chosen backend, Caddy opens a connection (or reuses a pooled one) and forwards the request. It adds headers such as X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host so the backend knows who the original client was.</li><li><strong>Response forwarding.</strong> The backend answers. Caddy streams that response back to the client, applying any response handlers such as compression.</li></ol><h3>Understanding the Caddyfile</h3><p>A Caddyfile is made of <strong>site blocks</strong>. Each block starts with an address and contains <strong>directives</strong> in braces. A directive is a name followed by its arguments. Useful commands: caddy run starts Caddy in the foreground, caddy validate checks a file, caddy fmt formats it and caddy reload applies a new config to a running server.</p><p>The examples below use :8080 or an explicit http:// address, so they run on a laptop with no extra setup.</p><h3>1. Basic static file server</h3><pre>:8080 {<br>    root * /var/www/site<br>    encode gzip<br>    file_server<br>}</pre><ul><li>:8080 is the site address: listen on port 8080 for any host name.</li><li>root * /var/www/site sets the folder that files are read from. The * means the rule applies to every request path.</li><li>encode gzip compresses responses with gzip when the client supports it. encode gzip zstd offers both.</li><li>file_server serves files from the root folder. Without it, Caddy would not answer with the files.</li></ul><h3>2. Reverse proxy to one backend</h3><pre>:8080 {<br>    reverse_proxy localhost:3000<br>}</pre><ul><li>reverse_proxy localhost:3000 sends every request to the application running on port 3000 and relays the response. The upstream may be written as host:port or with a scheme, such as <a href="http://localhost:3000.">http://localhost:3000.</a></li></ul><p>This is the smallest useful reverse proxy.</p><h3>3. Reverse proxy to several backend instances</h3><pre>:8080 {<br>    reverse_proxy localhost:3001 localhost:3002 localhost:3003<br>}</pre><p>Listing several upstreams turns on load balancing. By default Caddy picks a random upstream for each request.</p><h3>4. Host-based routing</h3><pre>http://app.localhost:8080 {<br>    reverse_proxy localhost:3000<br>}</pre><pre>http://admin.localhost:8080 {<br>    reverse_proxy localhost:5000<br>}</pre><ul><li>Each block has its own host name. Caddy matches the incoming Host header to a block.</li><li>The http:// prefix tells Caddy to serve plain HTTP on this address. Without it, Caddy treats a host name as a site to secure (covered in Part 2).</li></ul><p>Both sites share port 8080. Browsers resolve *.localhost to your own machine, so this works without editing the hosts file.</p><h3>5. Path-based routing</h3><pre>http://localhost:8080 {<br>    handle /api/* {<br>        reverse_proxy localhost:4000<br>    }</pre><pre>    handle_path /docs/* {<br>        root * /var/www/docs<br>        file_server<br>    }</pre><pre>    handle {<br>        reverse_proxy localhost:3000<br>    }<br>}</pre><ul><li>handle /api/* groups directives that run only for paths starting with /api/. The path is passed to the backend unchanged.</li><li>handle_path /docs/* does the same, but removes the /docs prefix first. A request for /docs/guide.html reads /var/www/docs/guide.html.</li><li>A final handle with no path matches everything else, so it acts as the fallback.</li><li>Caddy runs only the first matching handle block, so the order of specific-before-general matters.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-pXiUU2WzCQeXflVcL6aw.png" /></figure><h3>Load balancing with Caddy</h3><h3>Why run several instances?</h3><p>One process has a limit on the traffic it can handle, and if it crashes the service is down. Running several copies of an application spreads the load and lets you restart or upgrade one copy while the others keep answering.</p><h3>Load-balancing policies</h3><p>The policy decides which upstream gets the next request. Set it with lb_policy. The most useful ones:</p><ul><li>random (default): picks any upstream.</li><li>round_robin: takes the upstreams in turn.</li><li>least_conn: picks the upstream with the fewest active requests.</li><li>first: always the first available upstream, which gives you a primary with fallbacks.</li><li>ip_hash and cookie: send the same client to the same upstream (sticky sessions).</li><li>uri_hash and header: choose by the URI or by a header value.</li></ul><h3>A complete example</h3><pre>:8080 {<br>    reverse_proxy localhost:3001 localhost:3002 localhost:3003 {<br>        lb_policy round_robin<br>        lb_try_duration 5s<br>        lb_try_interval 250ms</pre><pre>        health_uri /health<br>        health_interval 10s<br>        health_timeout 2s<br>        health_status 2xx</pre><pre>        fail_duration 30s<br>        max_fails 3<br>        unhealthy_status 5xx<br>        unhealthy_latency 3s<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYWqnPpeNrbwZ0EeelLWgg.png" /></figure><p>Upstream failure handling</p><ul><li>lb_try_duration 5s: if no upstream can take the request, keep trying for up to five seconds before returning an error. The default is zero, which means Caddy does not retry.</li><li>lb_try_interval 250ms: wait this long between attempts.</li></ul><h3>Active health checks</h3><p>Caddy sends its own test requests to each upstream on a schedule, whether or not users are calling it.</p><ul><li>health_uri /health: the path to request. Setting it switches active checks on.</li><li>health_interval 10s: how often to check.</li><li>health_timeout 2s: how long to wait before the check counts as failed.</li><li>health_status 2xx: the status codes that count as healthy.</li></ul><p>An upstream that fails an active check is taken out of rotation until it passes again.</p><h3>Passive health checks</h3><p>Caddy watches real traffic and marks an upstream as down based on what happens to actual requests.</p><ul><li>fail_duration 30s: how long a failure is remembered. Passive checks are off until you set this.</li><li>max_fails 3: how many failures within that time mark the upstream as unavailable (the default is 1).</li><li>unhealthy_status 5xx and unhealthy_latency 3s: a 5xx answer, or a response slower than three seconds, counts as a failure.</li></ul><h3>What needs extra configuration</h3><p>Both features are built in and need no plugin. Neither is on by default for a single upstream. Load balancing starts when you list more than one upstream. Active checks start when you set health_uri (or health_port). Passive checks start when you set fail_duration. Retries on failure need lb_try_duration. Without that setting, a request that hits a dead upstream fails straight away.</p><p>Active checks catch a broken upstream before a user does. Passive checks cost nothing extra but need real traffic to notice a failure. Using both is common.</p><h3>Caddy, Nginx and Apache</h3><p>CaddyNginxApacheConfigurationShort Caddyfile; JSON and an API for automationBlock-based config; more lines for the same setupDirective-based; per-directory .htaccess filesReverse proxyOne directive with load balancing and health checks built inStrong; open-source Nginx has passive checks, active checks need NGINX Plus or a moduleThrough mod_proxy and its balancer modulesPerformanceVery good; Go runtime, typically more memory than NginxExcellent; event-driven C with a very small footprintGood; the event MPM is much better than the older prefork modelExtensibilityModules compiled into the binary with xcaddyLarge module ecosystem, many dynamicVery large, loadable modulesOperational complexityLow; one binary, runtime reload through the APIModerate; widely understood, much documentationModerate to high on large setupsCommon useSmall and mid-size services, containers, developer setupsHigh-traffic sites, edge proxying, mature platformsLegacy and PHP applications, shared hosting</p><p>None of these is better in every case. For most workloads the difference in raw speed will not matter, and a benchmark of your own traffic is worth more than a general claim. The choice is usually about the team’s skills, the existing setup and the features needed.</p><h3>Advantages and disadvantages</h3><h3>Strengths</h3><ul><li>A small, readable configuration. A working reverse proxy is three lines.</li><li>Load balancing, health checks, compression and HTTP/3 are included.</li><li>A single static binary is simple to install, copy and run in a container.</li><li>Configuration can be reloaded without dropping connections, and changed through the API.</li><li>Written in Go, a memory-safe language.</li></ul><h3>Limitations</h3><ul><li>A smaller community and fewer tutorials than Nginx and Apache.</li><li>Fewer third-party modules, and adding one means building a custom binary.</li><li>Memory use is usually higher than Nginx under very high load.</li><li>Teams with years of Nginx or Apache configuration have a migration cost.</li><li>Some advanced cases need JSON configuration instead of the Caddyfile.</li></ul><h3>When to use Caddy and when not to</h3><h3>A good fit</h3><ul><li><strong>A few services behind one entry point.</strong> A small team runs a frontend, an API and an admin app on one server.</li><li><strong>Containers and internal tools.</strong> One small binary with a short config file is easy to maintain.</li><li><strong>Local development.</strong> One Caddyfile can give every service a host name and route.</li><li><strong>Teams without a dedicated infrastructure person.</strong> There is less to learn and less to get wrong.</li></ul><h3>Think twice</h3><ul><li><strong>Very high-traffic edge.</strong> If you serve huge volumes and every megabyte counts, Nginx’s long record may be the safer choice.</li><li><strong>Existing Apache or PHP estate.</strong> If you depend on .htaccess or specific Apache modules, staying put is often cheaper.</li><li><strong>Heavy reliance on an ecosystem module</strong> that exists for Nginx or Apache but not for Caddy.</li><li><strong>Organisation standards.</strong> If your operations team already runs and monitors Nginx well, a second proxy adds cost.</li></ul><h3>Conclusion</h3><p>Caddy accepts requests, chooses a destination by host and path, forwards the request and returns the response. It can serve static files itself or act as a reverse proxy for one backend or many, with load balancing and health checks included. Its configuration is short enough that you can read a whole Caddyfile in a minute.</p><p>With the examples above you can set up a static site, a reverse proxy, host and path routing, and a load-balanced group of backends. In Part 2 we look at how Caddy handles HTTPS. In Part 3 we deploy it in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b444d78145dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forward Proxy vs Reverse Proxy Explained: How They Work, Trade-offs, and High Availability]]></title>
            <link>https://medium.com/@rameshkumarsgp/forward-proxy-vs-reverse-proxy-explained-how-they-work-trade-offs-and-high-availability-4b046ef15481?source=rss-c078d297bcc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b046ef15481</guid>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[forward-proxy]]></category>
            <dc:creator><![CDATA[Rameshkumar Shanmugam]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 04:24:46 GMT</pubDate>
            <atom:updated>2026-11-26T04:27:55.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aY8QA8O7j78OAlrvVx0ccw.jpeg" /></figure><p>When building a backend application, we usually start with something simple: a client sends an HTTP request directly to our backend service, and the backend returns a response.</p><p>For example:</p><ul><li>A Go API runs on localhost:8080</li><li>A Java API runs on localhost:8081</li><li>The client calls these APIs directly</li></ul><p>This works perfectly well when an application is small. But what happens when we have multiple backend services? What if we don’t want clients to know the internal addresses of those services? What if we need HTTPS, request routing, or load balancing?</p><p>This is where a <strong>Reverse Proxy</strong> becomes useful. Its counterpart, the <strong>Forward Proxy</strong>, solves the opposite problem: controlling the traffic that leaves our network. In this article we’ll cover both, starting with the reverse proxy and then moving to the forward proxy.</p><p>Let’s understand the problem first.</p><h3>1. The problem: clients directly accessing backend services</h3><p>Imagine three backend services, each running independently:</p><ul><li><strong>User Service</strong> handles user operations</li><li><strong>Loan Service</strong> handles loan operations</li><li><strong>Document Service</strong> handles document operations</li></ul><pre>Client<br>                    |<br>          +---------+---------+<br>          |         |         |<br>          v         v         v<br>      User API   Loan API   Document API<br>      :8081      :8082      :8083</pre><p>The client needs to know the address and port of every service:</p><pre>https://api.company.com:8081/users<br>https://api.company.com:8082/loans<br>https://api.company.com:8083/documents</pre><p>This creates a few problems:</p><ol><li><strong>Backend exposure:</strong> clients need to know the addresses of individual services.</li><li><strong>Configuration complexity:</strong> if a service moves to another host or port, clients may need changes.</li><li><strong>HTTPS management:</strong> each service may need its own TLS configuration and certificates.</li><li><strong>Load balancing:</strong> with multiple instances of a service, something must distribute the requests.</li><li><strong>Centralised request handling:</strong> concerns like access logging and routing are harder to manage consistently.</li></ol><p>We need a component between the client and our backend services. That component is a Reverse Proxy.</p><h3>2. What is a Reverse Proxy?</h3><p>A <strong>Reverse Proxy is a server that sits in front of backend servers and receives client requests on their behalf.</strong></p><p>Instead of talking to backend services directly, clients talk to the reverse proxy. The proxy forwards each request to the right backend and returns the backend’s response to the client.</p><pre>Client<br>                    |<br>                    v<br>              Reverse Proxy<br>                    |<br>          +---------+---------+<br>          |         |         |<br>          v         v         v<br>      User API   Loan API   Document API<br>      :8081      :8082      :8083</pre><p>Now the client needs to know only one public endpoint:</p><pre>https://api.company.com</pre><p>The client doesn’t need to know where the internal services are running.</p><h3>3. How does a Reverse Proxy work?</h3><p>Assume this setup:</p><ul><li>Reverse Proxy: api.company.com</li><li>User Service: localhost:8081</li><li>Loan Service: localhost:8082</li><li>Document Service: localhost:8083</li></ul><p>A client wants to fetch a document:</p><pre>GET https://api.company.com/documents/101</pre><p>Here is what happens:</p><ol><li>The client sends the request to api.company.com.</li><li>The reverse proxy receives it.</li><li>It checks the request path: /documents/101.</li><li>Based on its routing configuration, it forwards the request to Document Service.</li><li>Document Service processes the request and returns a response.</li><li>The reverse proxy sends that response back to the client.</li></ol><h3>Runtime request flow</h3><pre>Client                Reverse Proxy              Document Service<br>  |                         |                           |<br>  |  GET /documents/101     |                           |<br>  |------------------------&gt;|                           |<br>  |                         | match route /documents/*  |<br>  |                         |  forward request          |<br>  |                         |--------------------------&gt;|<br>  |                         |  200 OK + document data   |<br>  |                         |&lt;--------------------------|<br>  |  200 OK + document data |                           |<br>  |&lt;------------------------|                           |</pre><p>The reverse proxy does not run Document Service’s business logic. It receives the request and forwards it to the right backend.</p><h3>4. How does it know which backend to call?</h3><p>The proxy uses configuration rules:</p><ul><li>/users/* goes to User Service</li><li>/loans/* goes to Loan Service</li><li>/documents/* goes to Document Service</li></ul><p>Conceptually:</p><pre>IF request path starts with /users<br>    Forward to User Service<br>ELSE IF request path starts with /loans<br>    Forward to Loan Service<br>ELSE IF request path starts with /documents<br>    Forward to Document Service</pre><p>This is called <strong>request routing</strong>. A proxy can route on the URL path, the hostname, HTTP headers, and other request attributes it supports.</p><h3>5. Advantages of a Reverse Proxy</h3><h3>A. Single entry point</h3><p>Clients talk to one public endpoint instead of many service addresses. This simplifies client configuration and service discovery.</p><h3>B. Backend isolation</h3><p>Backend services can run on private networks instead of being exposed to the internet. Clients only need access to the proxy, which reduces the number of public entry points.</p><h3>C. TLS termination</h3><p>The proxy can handle the HTTPS connection with the client:</p><pre>Client -- HTTPS --&gt; Reverse Proxy -- HTTP or HTTPS --&gt; Backend</pre><p>The proxy terminates the client’s TLS connection and opens a separate connection to the backend. That internal connection can use HTTP or HTTPS depending on your security requirements.</p><h3>D. Load balancing</h3><p>If we run multiple instances of Document Service, the proxy can spread incoming requests across them.</p><pre>Reverse Proxy<br>                       |<br>            +----------+----------+<br>            |          |          |<br>            v          v          v<br>        Document   Document   Document<br>        Service 1  Service 2  Service 3</pre><p>This stops a single instance from handling every request.</p><h3>E. Centralised access logging</h3><p>The proxy can record request path, HTTP method, response status, request duration and client information in one place. Application logs are still needed to understand business operations and internal failures.</p><h3>F. Caching</h3><p>A proxy can cache eligible responses and serve repeat requests without calling the backend. This reduces backend load and improves response time.</p><p>Be careful, though. Caching personalised or sensitive responses incorrectly can expose one user’s data to another.</p><h3>6. Disadvantages of a Reverse Proxy</h3><h3>A. Single point of failure</h3><p>If we deploy only one proxy and it goes down, clients cannot reach the backend through that entry point, even if every backend service is healthy. We’ll fix this in the high-availability section.</p><h3>B. Additional network hop</h3><pre>Without proxy:  Client --&gt; Backend<br>With proxy:     Client --&gt; Reverse Proxy --&gt; Backend</pre><p>Every request passes through one more component, which adds some latency and processing overhead. That’s usually acceptable, but worth considering for latency-sensitive systems.</p><h3>C. Operational complexity</h3><p>We now have another component to configure, monitor, secure, scale and troubleshoot. Wrong routing, TLS settings, timeouts or header handling can break the application.</p><h3>D. Resource bottleneck</h3><p>If the proxy cannot handle the incoming traffic, it becomes the bottleneck even when the backends have spare capacity. The proxy layer must be sized and scaled properly.</p><h3>E. Security concentration</h3><p>The proxy is a critical entry point. If it is compromised or misconfigured, several backend services may be affected. Keep it patched, secured and monitored.</p><h3>7. When should we use a Reverse Proxy?</h3><p>Use one when:</p><ul><li>We have multiple backend services and want a single public entry point.</li><li>We need centralised TLS termination.</li><li>We want to distribute requests across multiple backend instances.</li><li>Backend services should not be directly reachable from the internet.</li><li>We need centralised routing, logging or caching.</li></ul><h3>When should we NOT use one?</h3><p>A reverse proxy is not mandatory. We may not need a dedicated one when:</p><ul><li>It is a small application with one backend service.</li><li>Direct access is acceptable and exposure is properly controlled.</li><li>Our cloud platform already provides the ingress, TLS and routing we need.</li><li>Another proxy would only duplicate existing infrastructure.</li></ul><p>The goal is not to add a proxy because it is a common pattern. The goal is to add it when its capabilities justify the operational cost.</p><h3>8. What happens if the Reverse Proxy goes down?</h3><p>This is an important production question. Take this architecture:</p><pre>Client<br>                    |<br>                    v<br>              Reverse Proxy<br>                    |<br>          +---------+---------+<br>          |         |         |<br>          v         v         v<br>       User       Loan     Document<br>       Service   Service   Service</pre><p>Now the proxy process crashes, or its machine becomes unavailable.</p><ol><li>The client sends a request.</li><li>The request cannot reach the proxy.</li><li>It never reaches any backend service.</li><li>The client gets a connection error or a timeout.</li></ol><p>The backends might be perfectly healthy, yet the application is unavailable through that entry point. This is why a single reverse proxy is a <strong>Single Point of Failure (SPOF)</strong>.</p><h3>How do we overcome this?</h3><p>Don’t run only one proxy. Run multiple proxy instances and put a highly available load balancer in front of them.</p><pre>Clients<br>                 |<br>                 v<br>   Highly Available Load Balancer<br>          |              |<br>          v              v<br>   Reverse Proxy 1   Reverse Proxy 2<br>          |              |<br>          +------+-------+<br>                 v<br>          Backend Services</pre><p>Now:</p><ul><li>If Reverse Proxy 1 goes down, the load balancer stops sending it traffic.</li><li>Reverse Proxy 2 keeps serving requests.</li><li>Backend services stay reachable through the healthy proxy.</li></ul><p>The load balancer must also be highly available. Otherwise we have only moved the single point of failure one layer up. In the cloud, a managed load balancer that spans multiple instances or availability zones does this for you.</p><h3>How does the load balancer know a proxy is down?</h3><p>Through <strong>health checks</strong>. The load balancer periodically checks each proxy:</p><pre>Load Balancer<br>    |<br>    +--&gt; Reverse Proxy 1: Healthy<br>    |<br>    +--&gt; Reverse Proxy 2: Unhealthy</pre><p>If Reverse Proxy 2 stops responding, it is removed from the pool and traffic goes only to healthy instances. When it recovers, it is added back.</p><h3>What if a backend service goes down?</h3><p>That is a different failure. Suppose all proxies are healthy but Document Service instance 1 is down.</p><pre>Reverse Proxy<br>                    |<br>          +---------+---------+<br>          |         |         |<br>          v         v         v<br>       Document  Document  Document<br>       Service 1 Service 2 Service 3<br>       DOWN      Healthy   Healthy</pre><p>With multiple Document Service instances, the proxy can skip the unhealthy one and send traffic to a healthy one. This needs suitable health checks or failure detection and load-balancing configuration.</p><h3>High-availability checklist</h3><ol><li>Run multiple proxy instances.</li><li>Put a highly available load balancer in front of them.</li><li>Configure health checks.</li><li>Spread instances across availability zones where possible.</li><li>Monitor proxy availability, latency, error rates and resource usage.</li><li>Keep proxy configuration consistent across instances.</li><li>Test failover instead of assuming it works.</li></ol><p><strong>Remember:</strong> multiple backend instances protect against backend failures. Multiple proxy instances protect against proxy failures. You need to consider both layers.</p><h3>9. What is a Forward Proxy?</h3><p>So far we have covered the reverse proxy, which handles incoming traffic on behalf of backend servers. A forward proxy serves a different purpose.</p><p>A <strong>Forward Proxy sits between clients and external servers and forwards outbound requests on behalf of those clients.</strong></p><p>Consider a company where backend services are not allowed to talk directly to external organisations. Our Document Service needs to call external providers such as DigiLocker or Protean.</p><pre>Without a forward proxy:</pre><pre>Document Service --&gt; DigiLocker / Protean</pre><pre>With a forward proxy:</pre><pre>Document Service --&gt; Corporate Forward Proxy --&gt; DigiLocker / Protean</pre><p>Document Service sends its outbound request to the forward proxy. The proxy forwards it to the provider according to company policy, then relays the response back.</p><h3>10. Advantages of a Forward Proxy</h3><ul><li><strong>Centralised outbound access control:</strong> allow DigiLocker and Protean, block unknown external domains.</li><li><strong>Centralised monitoring and auditing:</strong> outbound traffic is logged in one place, so security and operations teams can see which external systems are being accessed.</li><li><strong>Security policy enforcement:</strong> depending on its capabilities, a forward proxy can enforce destination filtering, malware inspection and data-loss prevention.</li><li><strong>Hides internal client addresses:</strong> external destinations see the proxy’s public address instead of each client’s internal one. This centralises your outbound network identity, but it is not complete anonymity.</li></ul><h3>11. Disadvantages of a Forward Proxy</h3><ul><li><strong>Additional network hop:</strong> every outbound request adds latency and processing overhead.</li><li><strong>Configuration complexity:</strong> applications and HTTP clients must be configured to use the proxy. Proxy authentication, certificates, timeouts and supported protocols all need attention.</li><li><strong>Single point of failure:</strong> if all outbound traffic depends on one forward proxy and it goes down, services lose contact with external providers.</li><li><strong>Centralised bottleneck:</strong> if the proxy can’t handle the outbound volume, it slows down multiple services.</li><li><strong>Troubleshooting complexity:</strong> an outbound failure can come from the application, the proxy, the network, DNS, TLS or the provider. The proxy is one more thing to investigate.</li></ul><h3>12. When should we use a Forward Proxy?</h3><p>Use one when:</p><ul><li>The organisation needs centralised control over outbound internet access.</li><li>Backend services must reach only approved external providers.</li><li>Security teams need centralised outbound monitoring.</li><li>Compliance or network policy requires controlled egress.</li><li>Multiple applications need a common outbound gateway.</li></ul><h3>When should we NOT use one?</h3><ul><li>There is no requirement for centralised outbound control.</li><li>Applications call only a few known destinations and network-level egress controls are enough.</li><li>The proxy adds unacceptable latency or operational complexity.</li><li>The protocol or traffic type isn’t supported by the chosen proxy.</li></ul><p>A forward proxy should solve a real security, compliance or network-management requirement, not be added without a clear purpose.</p><h3>13. What happens if the Forward Proxy goes down?</h3><pre>Document Service --&gt; Forward Proxy --&gt; External Provider</pre><p>If the forward proxy goes down:</p><ol><li>Document Service sends an outbound request.</li><li>The connection to the proxy fails or times out.</li><li>The request never reaches the provider.</li><li>The operation fails unless the application has a recovery strategy.</li></ol><p>The provider may be perfectly healthy. The failure is in our outbound network path.</p><h3>How do we overcome this?</h3><p>The same high-availability principle applies: deploy multiple proxy instances.</p><pre>Document Service<br>       |<br>       v<br>Outbound Load Balancer<br>    |          |<br>    v          v<br>Forward     Forward<br>Proxy 1     Proxy 2<br>    |          |<br>    +----+-----+<br>         v<br> External Providers</pre><p>The outbound load balancer spreads traffic across healthy forward proxies. If one fails, traffic goes to another.</p><p>Other things to consider:</p><ul><li>Configure health checks.</li><li>Monitor connection failures and proxy latency.</li><li>Use connection timeouts.</li><li>Retry transient failures carefully.</li><li>Don’t blindly retry non-idempotent operations.</li><li>Consider a circuit breaker to stop repeated calls to an unavailable dependency.</li></ul><h3>Should we bypass the proxy if it goes down?</h3><p>Not necessarily. If the company requires all outbound traffic to pass through the proxy for security or compliance, bypassing it could violate that policy. This is a design decision:</p><ul><li><strong>Fail closed:</strong> block outbound traffic when the proxy is unavailable. This preserves the security policy but affects availability.</li><li><strong>Fail open:</strong> allow direct outbound traffic when the proxy is unavailable. This improves availability but can bypass security controls.</li></ul><p>For mandatory corporate egress policies, fail closed is generally the safer choice, unless an explicitly approved alternative path exists.</p><h3>14. Forward Proxy vs Reverse Proxy</h3><p>Both are proxy servers, but they solve different problems.</p><ul><li><strong>Represents:</strong> a forward proxy represents clients; a reverse proxy represents backend servers.</li><li><strong>Traffic direction:</strong> forward is outbound; reverse is inbound.</li><li><strong>Sits in front of:</strong> forward sits in front of clients; reverse sits in front of backend services.</li><li><strong>Main purpose:</strong> forward controls outbound access; reverse manages incoming requests.</li><li><strong>Typical use:</strong> forward for corporate internet access and egress control; reverse for routing, TLS termination and load balancing.</li><li><strong>Failure impact:</strong> if a forward proxy fails, external communication may fail; if a reverse proxy fails, incoming application traffic may fail.</li></ul><p>The easiest way to remember it:</p><ul><li><strong>Forward Proxy:</strong> controls how clients reach external systems.</li><li><strong>Reverse Proxy:</strong> controls how external clients reach our backend systems.</li></ul><h3>15. Final mental model</h3><p>Think of a reverse proxy as the <strong>reception desk</strong> of an organisation. Visitors don’t need to know where every employee sits or which department handles their request. They tell the receptionist what they need, and the receptionist directs them to the right department.</p><p>A forward proxy is more like a <strong>company-controlled exit gate</strong>. Employees who need to reach external locations go through that gate, where the organisation can enforce its policies.</p><p>Both add a component to the communication path. Both give useful capabilities, and both bring availability, performance, security and operational considerations.</p><p><strong>The key takeaway:</strong></p><ul><li>Use a <strong>Reverse Proxy</strong> to manage and protect incoming traffic to backend services.</li><li>Use a <strong>Forward Proxy</strong> to manage and control outgoing traffic from clients or backend services.</li><li>Use <strong>multiple proxy instances</strong> and proper failover so the proxy never becomes a single point of failure.</li></ul><p>A proxy is not automatically a requirement. Introduce one when its benefits justify the extra infrastructure and operational responsibility.</p><p><em>If this helped, a clap or a follow helps others find it. Questions or corrections are welcome in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b046ef15481" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agile and Extreme Programming (XP), Explained Simply]]></title>
            <link>https://medium.com/@rameshkumarsgp/agile-and-extreme-programming-xp-explained-simply-e07f9994f6a8?source=rss-c078d297bcc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e07f9994f6a8</guid>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[extreme-programming]]></category>
            <dc:creator><![CDATA[Rameshkumar Shanmugam]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 05:54:53 GMT</pubDate>
            <atom:updated>2026-10-16T06:05:11.818Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hm9gbwkuVaY00SFGoX8N8A.png" /></figure><p><em>Agile delivers a small piece, shows it to the customer, then adjusts. The plan-everything approach shows the customer nothing until the end.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6K2kazSMrnEg8B-ejp5PKw.png" /></figure><p>Agile is a way of building software in small steps. Extreme Programming (XP) is one Agile method that tells you how to write the code itself.</p><p>This guide explains the four Agile values, the twelve principles, and the practices of XP. It ends with a worked example you can follow step by step.</p><h3>The story: a wedding cake</h3><p>A customer orders a wedding cake for a party three months away.</p><p><strong>Plan everything first.</strong> The baker writes a full plan, bakes the whole cake in secret, and delivers it on the day. The customer sees it for the first time at the party. They wanted lemon, not chocolate. It is too late to change anything.</p><p><strong>The Agile way.</strong> The baker bakes one small sample tier, and the customer tastes it the same week. The customer says “less sugar, and make it lemon.” The baker adjusts the next tier. After a few rounds the cake matches what the customer wants.</p><p><strong>The XP way.</strong> The baker goes further. Two bakers work side by side and check each other. They write down the taste test before they bake, so they know what “good” means. They bake in small batches and put each tier into the cake right away, so a bad tier is found at once.</p><p>Keep this story in mind. Every idea below is a version of it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGavqZOaxOil0vtI3-1IzQ.png" /></figure><p>Agile started in 2001, when a group of software developers wrote the Agile Manifesto. Their problem was common at the time. Teams planned for months, built for months, and delivered software that no longer matched what users needed.</p><p>Agile replaces one long plan with many short rounds. Each round is a plan, a build and a review. After every round the team has working software and real feedback.</p><p>Agile is not a single process. It is a set of values and principles. Methods such as Scrum, Kanban and XP are different ways to put them into practice.</p><h3>2. The four Agile values</h3><p>The Manifesto says: “while there is value in the items on the right, we value the items on the left more.” The right-hand side still matters. The left-hand side wins when the two conflict.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*grjLNG9oKLrq73EkJOiGJQ.png" /></figure><h3>3. The twelve Agile principles</h3><p>The Manifesto lists twelve principles behind the four values. Here they are grouped into four themes, in plain words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdnLZsAZ8aZEtvKAVA3FoQ.png" /></figure><h3>4. What is Extreme Programming (XP)?</h3><p>Extreme Programming is an Agile method that focuses on how developers write and test code. Kent Beck created it in the late 1990s, and it was described in his 1999 book <em>Extreme Programming Explained</em>.</p><p>The idea behind the name is to take good practices and turn them up to the maximum:</p><ul><li>Code reviews are good, so review the code all the time. That is pair programming.</li><li>Testing is good, so test first and test every day. That is test-driven development.</li><li>Integrating code is good, so integrate many times a day. That is continuous integration.</li></ul><p>Scrum organises the work: roles, meetings and sprints. XP organises the engineering. Many teams use both together.</p><h3>5. The five XP values</h3><p>XP rests on five values. The practices in the next section all come from them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjbA7EoJ9nV_OkqeI3Fkqw.png" /></figure><h3>6. The XP practices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjbA7EoJ9nV_OkqeI3Fkqw.png" /></figure><p>The original XP described twelve practices. Here they are with what you do and why it helps.</p><h3>7. How one XP iteration works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KCT9_jO9Tty_ed3h11y7Q.png" /></figure><p>XP work moves in a loop. One trip around the loop takes a short, fixed time, often one to two weeks.</p><p><em>Each iteration ends with working software in front of the customer, and the feedback decides what comes next.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3-zrIrB6yjHiXjMwJv3wQ.png" /></figure><ol><li><strong>User story.</strong> The customer describes one small piece of value, from the user’s point of view.</li><li><strong>Plan.</strong> In the planning game, the team picks the stories that fit into the next iteration.</li><li><strong>Build in pairs.</strong> Two developers write a failing test, then the code, then tidy it up.</li><li><strong>Integrate.</strong> The change is merged into the main code and every test runs.</li><li><strong>Release.</strong> A small working update goes to real users.</li><li><strong>Feedback.</strong> The customer reacts. The next stories are chosen with that feedback.</li></ol><h3>8. Test-driven development: red, green, refactor</h3><p>TDD is the practice people notice most. You write the test before the code, in three small steps that repeat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Z4fS1vxY5h_dcACUsfgPg.png" /></figure><p><em>Each loop is only a few minutes long. The tests are the safety net for every change.</em></p><p>Suppose the story is: “As a customer, I want to apply the code SAVE10 so that I get 10% off.” Here is the cycle in Java with JUnit 5.</p><p><strong>Red: write a test that fails.</strong> The class DiscountService does not exist yet, so the test cannot even compile. That counts as a failing test.</p><pre>class DiscountServiceTest {</pre><pre>    @Test<br>    void save10TakesTenPercentOffAHundred() {<br>        DiscountService service = new DiscountService();</pre><pre>        BigDecimal result = service.applyCode(&quot;SAVE10&quot;, new BigDecimal(&quot;100.00&quot;));</pre><pre>        assertEquals(new BigDecimal(&quot;90.00&quot;), result);<br>    }<br>}</pre><p><strong>Green: write the least code that passes.</strong> The smallest answer is to return 90.00. It looks silly, but it proves the test works.</p><pre>class DiscountService {</pre><pre>    BigDecimal applyCode(String code, BigDecimal total) {<br>        return new BigDecimal(&quot;90.00&quot;);<br>    }<br>}</pre><p><strong>Add another test.</strong> A second test expects 180.00 for a total of 200.00. It fails with the hard-coded answer, so now the real rule is needed.</p><pre>class DiscountService {</pre><pre>    private static final BigDecimal TEN_PERCENT_OFF = new BigDecimal(&quot;0.90&quot;);</pre><pre>    BigDecimal applyCode(String code, BigDecimal total) {<br>        if (&quot;SAVE10&quot;.equals(code)) {<br>            return total.multiply(TEN_PERCENT_OFF).setScale(2, RoundingMode.HALF_UP);<br>        }<br>        return total;<br>    }<br>}</pre><p><strong>Refactor: clean up while the tests stay green.</strong> The number 0.90 got a name. If you break something while tidying, a test turns red at once.</p><p>Money in Java is stored in BigDecimal, not double, because double cannot represent many decimal amounts exactly.</p><h3>9. A full example: the checkout discount</h3><p>Here is the whole flow for one feature, from request to release.</p><h3>10. What continuous integration does</h3><p>Continuous integration (CI) means everyone merges into the shared main code many times a day. Each merge triggers an automatic build and test run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGoXPJAQxI9zKZ3xGXl2Ow.png" /></figure><p><em>A failing build is the team’s top priority, so the main code is always in a working state.</em></p><p>The reason for merging often is simple. Two developers who work alone for weeks produce changes that clash when they meet. Merging small changes every day makes clashes small and easy to fix.</p><h3>11. Advantages and disadvantages of XP</h3><h3>Advantages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NUYCj-IqT09bGXfTfb_Y0Q.png" /></figure><h3>Disadvantages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bf7PwTf-N7c72Rb4GIqQFw.png" /></figure><h3>12. XP and Scrum</h3><p>XP and Scrum are both Agile, and they answer different questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1NodE-wXwkR0CWKQKheAg.png" /></figure><p>Teams often use Scrum for planning and meetings, and XP practices for coding.</p><h3>13. When does XP fit?</h3><p>XP fits when:</p><ul><li>Requirements change often or are unclear at the start.</li><li>The team is small, and its members can talk to each other every day.</li><li>A customer representative can join the team.</li><li>The team is willing to learn TDD and pairing.</li></ul><p>XP is a poor fit when:</p><ul><li>A fixed contract locks the scope and the price in advance.</li><li>No one can answer customer questions during the week.</li><li>The team will not write automated tests.</li></ul><h3>Recap</h3><ul><li>Agile builds software in small steps and uses feedback after each step.</li><li>Agile has four values and twelve principles. They favour people, working software, collaboration and change.</li><li>XP is the Agile method that tells developers how to code: tests first, work in pairs, merge often, clean up constantly and release small.</li><li>The practices support each other. Tests make refactoring safe, and CI makes small releases safe.</li><li>XP works best with a small team, a present customer and a team that keeps its discipline.</li></ul><h3>Sources</h3><ul><li>Agile Manifesto: <a href="https://agilemanifesto.org/">https://agilemanifesto.org/</a></li><li>Principles behind the Agile Manifesto: <a href="https://agilemanifesto.org/principles.html">https://agilemanifesto.org/principles.html</a></li><li>Kent Beck, <em>Extreme Programming Explained</em> (1999)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e07f9994f6a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Angular: Architecture, Compilation and Platforms]]></title>
            <link>https://medium.com/@rameshkumarsgp/understanding-angular-architecture-compilation-and-platforms-0d65292d16ea?source=rss-c078d297bcc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d65292d16ea</guid>
            <dc:creator><![CDATA[Rameshkumar Shanmugam]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 16:06:49 GMT</pubDate>
            <atom:updated>2026-10-13T16:06:49.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12UeBYFjyGdlN0KNKiihBg.png" /></figure><p><em>Components show the screen, services hold the logic, the runtime updates the browser.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMt-AXYuw-Wug4DDbJLHPw.png" /></figure><p>The router picks a component, the component gets its services through dependency injection, and the runtime turns the result into the page in the browser.</p><p>Angular is a framework for building web applications. It takes the code you write, turns it into files a browser can run, and then keeps the screen up to date while people use the app.</p><p>This document explains three things in plain words: how an Angular app is organised, how your code becomes something a browser can run, and where the finished app can run.</p><h3>A short story to hold in your head</h3><p>Think of a restaurant.</p><ul><li><strong>Recipe book</strong> = the code you write (TypeScript, HTML templates and CSS).</li><li><strong>Translator chef</strong> = the Angular compiler. Before the restaurant opens, this chef checks every recipe and rewrites it as plain kitchen steps.</li><li><strong>Kitchen</strong> = the Angular runtime. It cooks the dish when a guest orders and re-plates only the part that changed.</li><li><strong>Dining room</strong> = the browser. It shows the finished dish to the guest.</li><li><strong>Supplier</strong> = the backend server. It owns the real stock (your data) and the rules about who may take what.</li></ul><p>Every section below explains one of these roles in technical terms.</p><p><em>The compiler runs once, on the developer’s computer. The runtime runs on every user’s device.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyHvBT2x_xC1StDhKItuyQ.png" /></figure><p>Your code is translated once at build time. Users then run the result in the browser, and the backend supplies the real data.</p><h3>1. How an Angular app is organised</h3><p>An Angular app is built from a few parts. Each part has one job. Together they cover the screen, the logic, the data calls and the navigation.</p><h3>Why dependency injection helps</h3><p>Without DI, every component would create its own service, and two components would end up with two different copies of the same data. With DI, Angular creates the service once, according to your settings, and shares it. In tests you can hand over a fake service instead of the real one.</p><h3>How the screen stays up to date</h3><p>Angular supports two ways of noticing a change. The older way watches for events such as clicks and finished network calls, then checks the screen. The newer way uses <strong>signals</strong>: a signal is a value Angular watches directly, so it knows exactly which part of the screen to update. New projects can also run <strong>zoneless</strong>, which means Angular no longer relies on its older tracking library (zone.js) and depends on signals and explicit notifications instead.</p><p>The parts are not steps in a fixed order. Many components can share one service, and the router decides which components are on screen at any moment.</p><h3>2. What Angular code looks like</h3><p>Here is a small employee counter. Each click on the button adds one to the number on the screen.</p><pre>import { Component, signal } from &#39;@angular/core&#39;;</pre><pre>@Component({<br>  selector: &#39;app-employee-counter&#39;,<br>  template: `<br>    &lt;h2&gt;Employees: {{ count() }}&lt;/h2&gt;<br>    &lt;button (click)=&quot;increment()&quot;&gt;Add employee&lt;/button&gt;<br>  `<br>})<br>export class EmployeeCounterComponent {<br>  count = signal(0);</pre><pre>  increment() {<br>    this.count.update(n =&gt; n + 1);<br>  }<br>}</pre><p>What each part does:</p><ul><li>@Component(...) tells Angular that this class is a screen piece, and gives its settings.</li><li>selector: &#39;app-employee-counter&#39; is the tag name. Writing &lt;app-employee-counter&gt; in another template places this component there.</li><li>template is the HTML to show.</li><li>{{ count() }} shows the current value of count. Angular redraws it when the value changes.</li><li>(click)=&quot;increment()&quot; calls the increment method each time the button is clicked.</li><li>count = signal(0) creates a value, starting at 0, that Angular watches.</li><li>increment() adds 1 to that value.</li></ul><p>You never search for the heading and change its text yourself. You change the data, and Angular updates the screen.</p><p>In Angular 19 and later, components are standalone by default, so you do not need to write standalone: true. Older code adds it, and older projects group components inside NgModule classes. Both styles exist in real projects.</p><h3>3. How Angular code is compiled</h3><p>A browser runs JavaScript. It does not understand TypeScript types, Angular decorators such as @Component, or template syntax such as {{ count() }}. So the build converts your project into plain files first. It happens in four steps.</p><ol><li><strong>TypeScript compilation.</strong> TypeScript adds types to JavaScript. In const employeeCount: number = 10; the part : number is only for the build. The tools check it, then remove it. Types are checked while building and are not enforced while the app runs. If a server sends text where you expected a number, the types will not stop it.</li><li><strong>Angular compilation.</strong> The Angular compiler (called ngtsc when it works with TypeScript) reads decorators, templates, bindings and DI information. It checks the templates for mistakes, such as a property name that does not exist. Then it rewrites each template as JavaScript instructions that create and update the screen.</li><li><strong>Bundling and optimisation.</strong> The Angular CLI runs build tools (esbuild in current versions) to prepare the files for users. A production build can shrink the code (minification), remove code nobody calls (tree-shaking), split page-specific code into separate files that load only when needed (lazy loading), and process CSS and images.</li><li><strong>Browser execution.</strong> The browser downloads the HTML, CSS and JavaScript, runs the JavaScript, and Angular starts and draws the first screen. After that it responds to clicks and data changes.</li></ol><p>The result is a folder of static files. Any web server or CDN can host them. The compiler does not run again when a user clicks a button.</p><h3>4. AOT and JIT: two ways to compile templates</h3><p>Angular can compile your templates at two different moments.</p><p><strong>AOT does not mean the whole app becomes machine code.</strong> The output is still JavaScript. The browser’s JavaScript engine runs it, and that engine may interpret the code or speed it up while it runs.</p><p><strong>Two different things share the name JIT.</strong> One is Angular’s template compilation mode. The other is the browser engine’s own speed-up of JavaScript. The browser’s speed-up happens in both AOT and JIT Angular apps. The two have nothing to do with each other.</p><h3>5. The Angular runtime</h3><p>The compiler prepares the app. The runtime makes it work while people use it.</p><p>The runtime:</p><ul><li>creates components and directives</li><li>finds and supplies the services each class needs (dependency injection)</li><li>connects data to the screen and handles events such as clicks</li><li>updates the screen when data changes</li><li>runs component lifecycle steps, such as “this component was created” and “this component is removed”</li><li>runs the router and other framework features</li></ul><p>Three roles, side by side:</p><p>Angular builds on the browser. It does not replace the JavaScript engine or the operating system.</p><h3>6. Where an Angular app can run</h3><p>Angular’s main target is the web. The same web code can be delivered in five ways.</p><p>Support for these targets does not mean they all behave the same. Device features, background work, offline behaviour and store publishing depend on the shell around the app and its plugins.</p><h3>7. How an Angular app runs in production</h3><p>Take a banking web app with a login page, an account dashboard and a transaction history.</p><ol><li>A developer writes components, templates and services.</li><li>The build compiles and optimises them. The files are published to a web server or CDN.</li><li>A customer opens the site. The browser downloads the files and runs them.</li><li>Angular shows the login page, checks that required fields are filled, and moves between pages.</li><li>When the customer asks for transactions, Angular sends a request over HTTPS to a backend API.</li><li>The backend checks who the customer is, applies the business rules, reads the database and returns the data. Angular shows it.</li></ol><p><strong>Security rule.</strong> Hiding a button in Angular is not security. Anyone can send requests to your API without using your screen. The backend must check permission on every request. Angular’s client-side checks only make the screen friendlier, for example by showing an error before the form is sent.</p><p>Angular handles the screen, client-side validation, navigation and frontend state. It does not give you a backend, a database or a login server. You build or buy those separately.</p><h3>8. The development toolchain</h3><p>Common commands:</p><pre>ng new employee-app   # create a new project<br>cd employee-app<br>ng serve              # start a local server that rebuilds and reloads on every save<br>ng build              # produce the files you deploy</pre><p>ng serve is for development. ng build creates the optimised files for production and writes them to a folder, ready for a web server or CDN.</p><h3>9. How Angular differs from native mobile development</h3><p>The difference is where the app runs and how it draws the screen.</p><ul><li><strong>Angular</strong> runs in a browser. It builds the UI from HTML and CSS.</li><li><strong>A native app</strong> runs inside the phone’s operating system and uses the phone’s own UI controls and rules.</li></ul><p>On a phone, Angular usually runs inside a WebView in a native shell. The app is still web code. The shell lends it some device features through plugins. Building the screen from native controls is a different approach.</p><p>This changes five things you plan for:</p><ul><li><strong>Navigation:</strong> the browser’s URL and history, not the phone’s built-in screen stack.</li><li><strong>Rendering:</strong> web layout and CSS, not native components.</li><li><strong>Device access:</strong> only what the shell and its plugins expose.</li><li><strong>Performance:</strong> limited by the WebView, which matters for heavy animation or graphics.</li><li><strong>Release:</strong> a URL for web, and store review if you package it as an app.</li></ul><h3>10. Angular, Flutter and native: comparison</h3><p>I removed rows from the original that said the same thing in all three columns, such as backend communication, which uses HTTP clients and APIs everywhere.</p><h3>Three things to remember</h3><ol><li><strong>Angular compiler:</strong> prepares your TypeScript and templates before users arrive. The result is JavaScript that a JavaScript engine runs.</li><li><strong>Angular runtime:</strong> runs in the browser. It manages components, dependency injection, data bindings and screen updates.</li><li><strong>Angular platform:</strong> mainly the web. Phone and desktop apps are the same web code placed inside a wrapper such as Capacitor or Electron.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d65292d16ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication & Authorization Module — Spring Boot]]></title>
            <link>https://medium.com/@rameshkumarsgp/authentication-authorization-module-spring-boot-29ce4f449436?source=rss-c078d297bcc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/29ce4f449436</guid>
            <dc:creator><![CDATA[Rameshkumar Shanmugam]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 06:08:42 GMT</pubDate>
            <atom:updated>2026-10-12T06:08:42.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FgpXDZQMcF0DIgjAQn3ebA.png" /></figure><h3>1. Purpose</h3><p>This document is a foundation for designing an authentication and authorization module for a Spring Boot application.</p><p>The goal is to first understand the concepts, available approaches/tools, and responsibilities before writing implementation code.</p><h3>2. Authentication vs Authorization</h3><p>The easiest mental model is:</p><blockquote><strong><em>Authentication (AuthN) = Who are you?</em></strong><em><br></em><strong><em>Authorization (AuthZ) = What are you allowed to do?</em></strong></blockquote><h3>Authentication</h3><p>Authentication verifies the identity of an entity.</p><p>Examples:</p><ul><li>Username + password</li><li>Mobile number + OTP</li><li>Email + OTP</li><li>Passkey</li><li>TOTP</li><li>Security key</li><li>Social login / OpenID Connect</li></ul><p>OWASP defines authentication as the process of verifying that an individual, entity, or website is who or what it claims to be.</p><p>Source: <a href="https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html">https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html</a></p><h3>Example</h3><pre>Mobile number<br>      +<br>     OTP<br>      |<br>      v<br>&quot;Does this person control this phone?&quot;<br>      |<br>      v<br>      YES<br>      |<br>      v<br>Authenticated User</pre><p>Authentication answers:</p><pre>WHO ARE YOU?</pre><h3>3. Authorization</h3><p>Authorization determines whether an already-identified user/entity is allowed to perform a requested action or access a resource.</p><p>OWASP explicitly distinguishes authorization from authentication: being authenticated does not mean the user is allowed to access every resource or perform every operation.</p><p>Source: <a href="https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html">https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html</a></p><h3>Example</h3><pre>User = user-123<br>Role = CUSTOMER</pre><pre>GET /accounts/account-456</pre><pre>Is user-123 allowed to access account-456?<br>             |<br>       +-----+-----+<br>       |           |<br>      YES          NO<br>       |           |<br>       v           v<br>    200 OK      403 Forbidden</pre><p>Authorization answers:</p><pre>WHAT CAN YOU DO?</pre><h3>4. Authentication and Authorization Together</h3><p>The important sequence is:</p><pre>Authentication<br>      ↓<br>Identity<br>      ↓<br>Token<br>      ↓<br>Authorization<br>      ↓<br>Permission<br>      ↓<br>Business operation</pre><h3>5. Where Does JWT Fit?</h3><p>JWT is <strong>not authentication itself</strong>.</p><p>JWT is a token format that can carry claims about an authenticated subject.</p><p>A common architecture is:</p><p>A JWT commonly contains claims such as:</p><pre>{<br>  &quot;sub&quot;: &quot;user-123&quot;,<br>  &quot;iss&quot;: &quot;https://auth.example.com&quot;,<br>  &quot;aud&quot;: &quot;account-api&quot;,<br>  &quot;scope&quot;: &quot;account:read account:write&quot;,<br>  &quot;exp&quot;: 1790000000<br>}</pre><p>The exact claims depend on the authorization server and design.</p><h3>6. Authentication Flow</h3><p>A typical authentication flow:</p><h3>7. Authorization Flow</h3><p>After authentication:</p><p>A useful distinction:</p><pre>401 = Authentication problem<br>     &quot;I don&#39;t accept/recognize your authentication.&quot;</pre><pre>403 = Authorization problem<br>     &quot;I know who you are, but you are not allowed.&quot;</pre><h3>8. What Tools / Technologies Are Available?</h3><p>There are several ways to build an authentication system.</p><h3>Option A — Spring Security</h3><p><strong>Type:</strong> Open source framework</p><p>Spring Security is the core security framework for Spring applications.</p><p>It provides support for:</p><ul><li>Authentication</li><li>Authorization</li><li>Security filters</li><li>Method security</li><li>OAuth 2.0</li><li>OpenID Connect</li><li>Resource Server</li><li>JWT validation</li><li>Session security</li><li>Password authentication</li></ul><p>Spring Security supports OAuth 2.0 Resource Server using both JWT and opaque bearer tokens.</p><p>Source: <a href="https://docs.spring.io/spring-security/reference/servlet/oauth2/">https://docs.spring.io/spring-security/reference/servlet/oauth2/</a></p><h3>Important</h3><p>Spring Security is primarily a <strong>security framework</strong>.</p><p>It does not automatically mean you have a complete identity provider.</p><p>Think:</p><pre>Spring Security<br>      |<br>      +-- Protect my API<br>      +-- Validate tokens<br>      +-- Check authorities<br>      +-- Enforce endpoint access<br>      +-- Integrate with an Identity Provider</pre><h3>9. Keycloak</h3><p><strong>Type:</strong> Open source Identity and Access Management platform</p><p>Keycloak can provide:</p><ul><li>User management</li><li>Login</li><li>Identity management</li><li>Roles</li><li>Groups</li><li>OAuth 2.0</li><li>OpenID Connect</li><li>Token issuance</li><li>Single Sign-On</li><li>Federation/integration with external identity systems</li></ul><p>Typical architecture:</p><p>Keycloak becomes the Identity Provider / Authorization Server while Spring Boot applications act as protected resource servers.</p><p>Official site:</p><p><a href="https://www.keycloak.org/">https://www.keycloak.org/</a></p><h3>10. Spring Authorization Server</h3><p><strong>Type:</strong> Open source Spring project/framework</p><p>Spring Authorization Server is used when you want to build your <strong>own OAuth 2.0 Authorization Server / OpenID Connect Provider</strong> using Spring.</p><p>It is different from Spring Security itself.</p><pre>Spring Security<br>     |<br>     +-- Protect applications<br>     +-- Resource Server<br>     +-- Client<br>     +-- Authentication/Authorization mechanisms<br></pre><pre>Spring Authorization Server<br>     |<br>     +-- Build an Authorization Server<br>     +-- Issue OAuth 2.0 tokens<br>     +-- Support OIDC</pre><p>Official documentation:</p><p><a href="https://docs.spring.io/spring-security/reference/servlet/oauth2/authorization-server/">https://docs.spring.io/spring-security/reference/servlet/oauth2/authorization-server/</a></p><p>Current Spring documentation provides a Spring Boot starter:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-oauth2-authorization-server&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h3>11. Managed / SaaS Identity Providers</h3><p>Instead of operating your own identity platform, you can use a managed provider.</p><p>Common examples include:</p><p>The exact capabilities, pricing, limits, and supported features vary by provider and plan.</p><h3>12. Two Major Architecture Choices</h3><h3>Choice 1 — Build Your Own Authentication Server</h3><p>Possible technologies:</p><ul><li>Spring Security</li><li>Spring Authorization Server</li><li>Your user database</li><li>JWT</li><li>OTP provider</li><li>Redis / database for temporary authentication state</li></ul><p>You own the implementation and security responsibilities.</p><h3>13. Choice 2 — Use an Identity Provider</h3><p>Examples:</p><ul><li>Keycloak</li><li>Auth0</li><li>Okta</li><li>Amazon Cognito</li><li>Microsoft Entra External ID</li></ul><p>The application delegates identity management/token issuance to the identity platform.</p><h3>Spring Authorization Server vs Keycloak/Auth0/Okta — alternatives, not both</h3><p>If you use Spring Authorization Server to build and run your own Authorization Server, you don’t also need Keycloak/Auth0/Okta for that same role.</p><p>They are alternative ways of providing the Authorization Server / Identity Provider layer — Choice 1 (build your own) typically uses Spring Authorization Server; Choice 2 (use an identity provider) uses one of Keycloak/Auth0/Okta/etc. You don’t combine them for the same role.</p><p><strong>Option 1 — Spring Authorization Server</strong></p><pre>Your infrastructure<br>                       │<br>                       ▼<br>          ┌────────────────────────┐<br>          │ Spring Authorization   │<br>          │ Server                 │<br>          │                        │<br>          │ OAuth 2.0              │<br>          │ OIDC                   │<br>          │ Token issuance         │<br>          │ Your authentication    │<br>          └───────────┬────────────┘<br>                       │<br>                     JWT<br>                       │<br>                       ▼<br>               Spring Boot APIs<br>                       │<br>                       ▼<br>               Spring Security</pre><p>Here:</p><ul><li>Spring Authorization Server → Authorization Server</li><li>Spring Security → protects your APIs</li><li>Your code/database → user/identity management as needed</li><li>Keycloak → not required</li></ul><p><strong>Option 2 — Keycloak</strong></p><pre>Keycloak<br>                      │<br>              Authorization Server<br>                      │<br>                OAuth 2.0 / OIDC<br>                      │<br>                    JWT<br>                      │<br>                      ▼<br>              Spring Boot APIs<br>                      │<br>                      ▼<br>              Spring Security</pre><p>Here:</p><ul><li>Keycloak → Authorization Server / IdP</li><li>Spring Security → protects your APIs</li><li>Spring Authorization Server → not required</li></ul><p><strong>So you can think of it as:</strong></p><pre>Authorization Server<br>                           │<br>             ┌─────────────┼─────────────┐<br>             │             │             │<br>          Keycloak      Spring AS      Auth0<br>             │             │             │<br>             └─────────────┼─────────────┘<br>                           │<br>                       Access Token<br>                           │<br>                           ▼<br>                    Spring Security<br>                           │<br>                           ▼<br>                         APIs</pre><p>You generally choose <strong>one</strong> provider for the Authorization Server role — not both.</p><h3>14. What Spring Boot API Usually Does</h3><p>A Spring Boot API can act as an OAuth 2.0 <strong>Resource Server</strong>.</p><p>For example:</p><pre>spring:<br>  security:<br>    oauth2:<br>      resourceserver:<br>        jwt:<br>          issuer-uri: https://auth.example.com</pre><p>Spring Security can then discover the authorization server metadata/JWK information and validate incoming JWT bearer tokens.</p><p>Spring Security’s current documentation describes validation of JWT signature, exp, nbf, and iss, and mapping scopes to authorities.</p><p>Source: <a href="https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html">https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html</a></p><h3>16. Role-Based Authorization</h3><p>One common model is RBAC.</p><p>Example:</p><pre>CUSTOMER<br>  ├── ACCOUNT_READ<br>  └── ACCOUNT_TRANSFER</pre><pre>SUPPORT<br>  ├── CUSTOMER_READ<br>  └── CUSTOMER_UPDATE</pre><pre>ADMIN<br>  ├── USER_READ<br>  ├── USER_UPDATE<br>  └── USER_DELETE</pre><h3>18. Authentication Module — Recommended Logical Components</h3><p>Before implementation, separate responsibilities.</p><p>Potential modules:</p><pre>authentication/<br>├── login<br>├── credentials<br>├── otp<br>├── token<br>├── refresh-token<br>├── session<br>└── identity</pre><pre>authorization/<br>├── roles<br>├── permissions<br>├── scopes<br>├── policies<br>└── resource-access</pre><p>The exact package structure should be decided after choosing the architecture.</p><h3>19. Token Types</h3><p>A common OAuth-style design uses:</p><h3>Access Token</h3><p>Short-lived token used to access APIs.</p><pre>Client<br>  |<br>  | Authorization: Bearer &lt;access-token&gt;<br>  v<br>API</pre><h3>Refresh Token</h3><p>Longer-lived credential used to obtain a new access token.</p><p>Access-token and refresh-token lifecycle design should be treated as a separate security concern from basic JWT validation.</p><h3>20. JWT Signing Models</h3><p>There are two important approaches.</p><h3>Symmetric</h3><p>Example:</p><pre>HS256</pre><pre>Auth Server<br>    |<br>    | shared secret<br>    v<br>sign JWT</pre><pre>API<br>    |<br>    | same shared secret<br>    v<br>verify JWT</pre><p>The same secret can sign and verify.</p><h3>Asymmetric</h3><p>Example:</p><pre>RS256 / ES256</pre><pre>Auth Server<br>    |<br>    | Private Key<br>    v<br>sign JWT</pre><pre>API<br>    |<br>    | Public Key<br>    v<br>verify JWT</pre><p>This is particularly useful when many APIs need to validate tokens but should not possess the private signing key.</p><p>Spring Security’s resource-server documentation supports JWT validation using public keys/JWKs and issuer configuration.</p><h3>21. Recommended Learning/Design Order</h3><p>Do not start by writing controllers.</p><p>Understand these in order:</p><pre>1. Authentication<br>       ↓<br>2. Authorization<br>       ↓<br>3. OAuth 2.0<br>       ↓<br>4. OpenID Connect<br>       ↓<br>5. Access Token<br>       ↓<br>6. Refresh Token<br>       ↓<br>7. JWT<br>       ↓<br>8. JWT signing / verification<br>       ↓<br>9. Spring Security<br>       ↓<br>10. Resource Server<br>       ↓<br>11. Roles / Permissions / Scopes<br>       ↓<br>12. Resource-level authorization<br>       ↓<br>13. Session / token lifecycle<br>       ↓<br>14. Key management / rotation<br>       ↓<br>15. Audit / rate limiting / security controls</pre><h3>22. High-Level Architecture for the Module</h3><p>A mature design could look like:</p><h3>23. Decision Table</h3><h3>24. Important Terminology</h3><pre>Authentication<br>    = Who are you?</pre><pre>Authorization<br>    = What are you allowed to do?</pre><pre>Identity Provider (IdP)<br>    = System that manages/establishes identities and authentication.</pre><pre>Authorization Server<br>    = OAuth 2.0 server that issues access tokens.</pre><pre>Resource Server<br>    = API that accepts access tokens and protects resources.</pre><pre>Access Token<br>    = Credential presented to an API.</pre><pre>Refresh Token<br>    = Credential used to obtain new access tokens.</pre><pre>JWT<br>    = A token representation/format.</pre><pre>OAuth 2.0<br>    = Authorization framework.</pre><pre>OpenID Connect<br>    = Identity layer built on OAuth 2.0.</pre><pre>Spring Security<br>    = Security framework for Spring applications.</pre><pre>Keycloak<br>    = Identity and access management platform.</pre><pre>Spring Authorization Server<br>    = Framework for building an OAuth 2.0 Authorization Server.</pre><h3>25. Key Takeaway</h3><p>The whole picture can be reduced to:</p><p>The most important architectural decision is <strong>not JWT vs non-JWT</strong>.</p><p>First decide:</p><blockquote><strong><em>Who owns authentication and token issuance?</em></strong></blockquote><p>Then decide:</p><blockquote><strong><em>Where and how is authorization enforced?</em></strong></blockquote><p>Then choose the technology:</p><pre>Build it<br>    ├── Spring Security<br>    └── Spring Authorization Server</pre><pre>or</pre><pre>Use an Identity Platform<br>    ├── Keycloak<br>    ├── Auth0<br>    ├── Okta<br>    ├── Amazon Cognito<br>    └── Microsoft Entra External ID</pre><p>For a production Spring Boot system, Spring Security is commonly the API security layer even when a separate Identity Provider is responsible for authentication and token issuance.</p><h3>26. What Runa Actually Uses Today</h3><p>This section connects the theory above to the real codebase, so this doc doesn’t stay purely hypothetical.</p><p>Runa picked <strong>Choice 1 — build your own authentication server</strong> (Section 12). There is no Keycloak, Auth0, Okta, Cognito, Entra, or any OIDC/SAML integration anywhere in the codebase.</p><pre>Mobile number + OTP (via Protean)<br>        │<br>        ▼<br>   user-service  (Authentication Module)<br>        │<br>        ▼<br>   Custom JWT — HS256, shared secret<br>        │<br>        ▼<br>   api-gateway  (verifies with the same secret)<br>        │<br>        ▼<br>   Business Logic</pre><p>Mapped onto this doc’s terms:</p><p>Current JWT claims are simpler than the OAuth-style example in Section 5:</p><pre>{<br>  &quot;sub&quot;: &quot;&lt;userId&gt;&quot;,<br>  &quot;iss&quot;: &quot;user-service&quot;,<br>  &quot;iat&quot;: 1790000000,<br>  &quot;exp&quot;: 1790003600,<br>  &quot;typ&quot;: &quot;access&quot;<br>}</pre><p>No scope, aud, or role/permission claims yet. That means <strong>authorization (Sections 15–17) is not implemented today</strong> — api-gateway only checks &quot;is this JWT valid,&quot; not &quot;is this user allowed to do X.&quot; Any endpoint-level or resource-level permission checks would need to be added on top of this.</p><p><strong>Known gap:</strong> OTP verification is temporarily bypassed in AuthenticationService.java — instead of calling Protean, the OTP is hardcoded to today&#39;s date (ddMMyy, IST). The real Protean calls are commented out in the same file, ready to be restored. This must be fixed before production use — right now anyone who knows today&#39;s date can complete login for any mobile number.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29ce4f449436" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Liquibase, Database Migrations, Live Deployments, and Rollout Strategies]]></title>
            <link>https://medium.com/@rameshkumarsgp/liquibase-database-migrations-live-deployments-and-rollout-strategies-47071b524fa2?source=rss-c078d297bcc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/47071b524fa2</guid>
            <dc:creator><![CDATA[Rameshkumar Shanmugam]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 06:07:57 GMT</pubDate>
            <atom:updated>2026-10-12T06:07:57.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4e0m0LnakPb2roc35RoEkg.png" /></figure><h3>1. Big picture</h3><p>For a Spring Boot production application, several different pieces work together:</p><p>The important distinction is:</p><ul><li><strong>CI/CD</strong> delivers/builds/tests/deploys the application.</li><li><strong>Rollout strategy</strong> controls how application versions are introduced to users.</li><li><strong>Liquibase</strong> manages database schema/data changes and tracks which migrations have run.</li><li><strong>Database engine</strong> actually executes SQL/DDL and controls locking, concurrency, storage, and physical changes.</li></ul><h3>2. What is Liquibase?</h3><p>Liquibase is a <strong>database schema change and version management tool</strong> (<a href="https://www.liquibase.org/get-started/core-usage/liquibase-core-concepts-author-database-changes">liquibase.org</a>).</p><p>A useful analogy is:</p><p>Suppose the database initially contains:</p><p>A new application version needs a phone column:</p><p>Instead of manually running a database command every time, you define a <strong>changelog</strong> made up of <strong>changesets</strong>. A changelog is Liquibase’s ordered list of changes; a changeset is the smallest unit of change inside it, and each one requires an id and an author — together with the changelog&#39;s file path, these form the changeset&#39;s unique identity (<a href="https://docs.liquibase.com/concepts/changelogs/home.html">docs.liquibase.com</a>).</p><p>Example structure:</p><pre>db/changelog/<br>├── db.changelog-master.yaml<br>├── 001-create-contact.yaml<br>└── 002-add-phone.yaml</pre><p>Example changeset (YAML):</p><pre>databaseChangeLog:<br>  - changeSet:<br>      id: 002<br>      author: ramesh<br>      changes:<br>        - addColumn:<br>            tableName: contacts<br>            columns:<br>              - column:<br>                  name: phone<br>                  type: varchar(20)<br>      rollback:<br>        - dropColumn:<br>            tableName: contacts<br>            columnName: phone</pre><p>The same changeset in <strong>formatted SQL</strong> (also officially supported, and popular with teams that prefer hand-written DDL):</p><pre>--liquibase formatted sql</pre><pre>--changeset ramesh:002<br>ALTER TABLE contacts ADD COLUMN phone VARCHAR(20);<br>--rollback ALTER TABLE contacts DROP COLUMN phone;</pre><blockquote><strong><em>Best practice:</em></strong><em> put exactly one change per changeset. If a changeset with multiple changes fails partway through, some databases will have already committed the earlier statements, leaving the schema in an inconsistent, hard-to-diagnose state (</em><a href="https://docs.liquibase.com/concepts/changelogs/changeset.html"><em>docs.liquibase.com</em></a><em>).</em></blockquote><h3>3. How does Liquibase know what to run?</h3><p>You normally do <strong>not</strong> tell Liquibase manually “run migration 002 now.”</p><p>Liquibase tracks every changeset it has already executed in the <strong>DATABASECHANGELOG</strong> table, which it creates automatically the first time it runs against a database (<a href="https://docs.liquibase.com/concepts/tracking-tables/databasechangelog-table.html">docs.liquibase.com</a>). On startup, Liquibase compares the changelog file against this table and executes only the changesets that are missing.</p><p>So when Liquibase runs, it determines which changesets have not yet been applied. This is why the migration does not need to be manually triggered for every deployment.</p><p>A second table, <strong>DATABASECHANGELOGLOCK</strong>, exists purely so that only one Liquibase process updates a given database at a time. Every update first checks and sets a lock row; a second concurrent Liquibase process waits until the lock is released before proceeding (<a href="https://docs.liquibase.com/pro/user-guide-4-33/what-is-the-database-changelog-lock-table">docs.liquibase.com</a>). This matters a lot for the rolling-deployment scenarios discussed later — see <a href="http://localhost:63342/runa/docs/medium/liquibase-migrations-and-deployment-rollouts/article-medium.html?_ijt=1csudg1sqnc8leolb1htss3i85&amp;_ij_reload=RELOAD_ON_SAVE#19-liquibase-safety-mechanisms-in-production">§19</a>.</p><h3>3.1 From an empty table to a tracked migration, step by step</h3><p><strong>Stage 0 — before Liquibase has ever run.</strong> Neither tracking table exists yet; there is nothing to compare against.</p><p><strong>Stage 1 — first run, one changeset in the changelog:</strong></p><pre>-- changeset dev:001-create-users-table<br>CREATE TABLE users (id BIGSERIAL PRIMARY KEY, name VARCHAR(255));</pre><p>Resulting table:</p><p><strong>Stage 2 — a new changeset is added</strong> to the changelog file (nothing has run yet):</p><pre>-- changeset dev:002-add-email-column<br>ALTER TABLE users ADD COLUMN email VARCHAR(255);</pre><p><strong>Stage 3 — next deployment starts:</strong></p><p>Liquibase never re-runs 001 — it only acts on what’s missing from the table. Resulting table after this second migration:</p><p>One row per successfully-run changeset, keyed by (ID, AUTHOR, FILENAME). Every future deployment repeats the same diff: read the changelog, read this table, run whatever&#39;s in the changelog but not yet in the table, insert a row the moment each one finishes.</p><blockquote><strong><em>Edge case:</em></strong><em> if a changeset’s SQL fails partway through, no row gets inserted for it, so the next deployment attempt tries that same changeset again from scratch — another reason the “one change per changeset” best practice in </em><a href="http://localhost:63342/runa/docs/medium/liquibase-migrations-and-deployment-rollouts/article-medium.html?_ijt=1csudg1sqnc8leolb1htss3i85&amp;_ij_reload=RELOAD_ON_SAVE#2-what-is-liquibase"><em>§2</em></a><em> matters, since a multi-statement changeset can leave the schema half-changed with nothing recorded to say so.</em></blockquote><h3>3.2 How the comparison decides “run” vs “skip”</h3><p>For every changeset, in changelog file order, Liquibase runs this decision:</p><p>This is really two checks layered on top of each other:</p><ol><li><strong>Identity check — has this changeset been seen at all?</strong> The lookup key is the triple (ID, AUTHOR, FILENAME). No matching row means it&#39;s brand new: run it, then insert a row.</li><li><strong>Integrity check — if it’s been seen, has it changed since?</strong> If a row is found, Liquibase still recalculates the MD5 checksum of the changeset’s current content and compares it against the row’s MD5SUM. Same checksum → skip silently. Different checksum → someone edited an already-executed changeset, and by default Liquibase treats this as fatal and stops the whole deployment rather than guess whether to re-run it.</li></ol><p>Two attributes change that default:</p><ul><li>runOnChange: true — turns a checksum mismatch from &quot;fatal error&quot; into &quot;re-run it.&quot; Useful for things like view/stored-procedure definitions that are expected to be updated in place.</li><li>runAlways: true — skips the checksum comparison entirely and executes every time, regardless of history. Rare — used for things like re-seeding reference data.</li></ul><p>Execution order is <strong>changelog file order</strong>, not insertion order in the table — ORDEREXECUTED just records the sequence changesets <em>were</em> historically applied in; it doesn&#39;t drive future runs. Every deployment re-walks the changelog top to bottom and applies this identity+checksum check per changeset independently.</p><p>One layer sits <em>before</em> this comparison even happens: <strong>preconditions</strong> (see <a href="http://localhost:63342/runa/docs/medium/liquibase-migrations-and-deployment-rollouts/article-medium.html?_ijt=1csudg1sqnc8leolb1htss3i85&amp;_ij_reload=RELOAD_ON_SAVE#19-liquibase-safety-mechanisms-in-production">§19</a>) are evaluated first, per changeset. If a precondition fails, Liquibase never reaches the identity/checksum check for that changeset — it marks it onFail: MARK_RAN (pretend it ran, insert the row anyway) or halts, depending on configuration.</p><h3>4. Where does Liquibase fit in Spring Boot?</h3><p>A simplified Spring Boot startup flow is:</p><p>The exact internal Spring Boot startup order has more details, but this is the useful mental model.</p><p>When the liquibase-core dependency is on the classpath, Spring Boot auto-configures Liquibase and runs it automatically during startup, provided spring.liquibase.enabled is not set to false (it defaults to true). By default it looks for a changelog at src/main/resources/db/changelog/db.changelog-master.yaml (or .xml) (<a href="https://docs.liquibase.com/community/get-started-5-0/install-liquibase-with-spring-boot">docs.liquibase.com</a>, <a href="https://docs.spring.io/spring-boot/api/java/org/springframework/boot/liquibase/autoconfigure/LiquibaseAutoConfiguration.html">docs.spring.io</a>):</p><pre>spring:<br>  liquibase:<br>    enabled: true<br>    change-log: classpath:db/changelog/db.changelog-master.yaml</pre><p>Liquibase can also be run as a <strong>separate migration job</strong> from the application itself, using the Liquibase CLI, Maven/Gradle plugin, or a dedicated container image. This is common when teams want database migration to be an explicit, independently-controlled deployment step rather than something embedded in every application instance’s startup path.</p><h3>5. CI/CD and Liquibase are not the same thing</h3><p>A CI/CD pipeline may do several things:</p><p>One possible setup — migration as its own job:</p><p>Another setup — migration embedded in the application:</p><p>The architecture determines which model is used.</p><h3>6. A live application before a deployment</h3><p>Imagine production currently has multiple instances of App v1:</p><p>The application instances normally share the same production database.</p><h3>7. Introducing App v2</h3><p>Suppose App v2 requires a new phone column.</p><p>During a rollout, there can temporarily be both versions:</p><p>The important point is:</p><blockquote><em>During a normal production rollout, App v1 and App v2 generally use the same production database.</em></blockquote><p>It is usually <strong>not</strong>:</p><p>because maintaining and synchronizing separate production databases creates a much harder data-consistency problem.</p><p>Different environments normally have separate databases:</p><h3>8. What happens when Liquibase adds a column?</h3><p>Suppose Liquibase executes:</p><pre>ALTER TABLE contacts<br>ADD COLUMN phone VARCHAR(20);</pre><p>A common misconception is that every database engine must do this:</p><p>That is <strong>not universally true</strong>.</p><p>The actual behavior depends on the database engine, its version, and the exact operation.</p><p>Factors can include:</p><ul><li>Database engine</li><li>Database version</li><li>Type of schema change</li><li>Table size</li><li>Existing indexes</li><li>Constraints</li><li>DDL algorithm supported by the engine</li><li>Existing transactions</li><li>Locks required by the operation</li><li>Whether data must be physically rewritten</li></ul><p>For some engines and some operations (e.g. ADD COLUMN with a NULL default on PostgreSQL ≥ 11, or MySQL 8&#39;s INSTANT DDL algorithm), adding a column can be primarily a metadata operation. Other changes may require substantial table/index rewrites.</p><p>Therefore, there is no universal answer such as: “Adding a column always takes X seconds.” Liquibase does not change this physics — it only decides <em>which</em> SQL runs and <em>when</em>; the engine still decides <em>how</em> that SQL executes.</p><h3>9. Liquibase vs database engine</h3><p>This distinction is extremely important.</p><p>Liquibase essentially says “execute this database change.” The database engine determines how that change is actually executed:</p><p>So:</p><blockquote><strong><em>Liquibase manages and tracks the migration; the database engine performs the actual database operation.</em></strong></blockquote><h3>10. What happens to incoming requests while a migration is running?</h3><p>This is the important production question. The database engine handles the DDL and normal requests according to its own concurrency and locking rules — Liquibase has no control over this once the SQL is submitted.</p><p>There are several possible outcomes depending on the operation.</p><h3>Case 1: Concurrent work is allowed</h3><p>The migration can run while normal requests continue, with only a short metadata/DDL lock:</p><h3>Case 2: A blocking lock is required</h3><p>Some schema changes require stronger locking. Requests that need the affected object may have to wait:</p><h3>Case 3: The schema change is incompatible</h3><p>If the old application expects something that the migration removes or changes, requests can fail:</p><p>This is why production schema changes must be planned together with application rollout — see <a href="http://localhost:63342/runa/docs/medium/liquibase-migrations-and-deployment-rollouts/article-medium.html?_ijt=1csudg1sqnc8leolb1htss3i85&amp;_ij_reload=RELOAD_ON_SAVE#13-expand--migrate--contract">§13</a>.</p><h3>11. Adding a column safely</h3><p>Before migration:</p><p>App v1 might execute:</p><pre>SELECT id, name, email<br>FROM contacts;</pre><p>Liquibase adds phone. After migration:</p><p>App v1 still works because it does not depend on phone. App v2 can use the new column:</p><p>This works precisely because the change is <strong>additive and nullable</strong> — nothing existing breaks. Contrast with §12.</p><h3>12. Why destructive migrations are dangerous</h3><p>Suppose App v1 still expects the email column, and a migration immediately does:</p><pre>ALTER TABLE contacts<br>DROP COLUMN email;</pre><p>while App v1 is still serving traffic.</p><p>This is why production database changes are commonly staged — see the expand/contract pattern next.</p><h3>13. Expand → Migrate → Contract</h3><p>A common production migration pattern, also called the <strong>expand-contract pattern</strong> (<a href="https://www.liquibase.com/technical-glossary/expand-contract-pattern">liquibase.com</a>), is:</p><p>Expanded into concrete steps:</p><p>The benefit is that old and new application versions can coexist during the transition. This trades a single quick migration for multiple smaller deploys, and a longer window where the application must tolerate both the old and new shape — use it for changes that would otherwise be breaking (renames, type changes, drops, NOT NULL additions), not for every migration.</p><p><strong>Example — renaming a column</strong> (a classic expand/contract case, since a plain RENAME COLUMN is instantly breaking for whichever app version doesn&#39;t expect it):</p><pre># Changeset 1 (EXPAND): add the new column, keep the old one<br>- changeSet:<br>    id: 010-add-email-address<br>    author: ramesh<br>    changes:<br>      - addColumn:<br>          tableName: contacts<br>          columns:<br>            - column:<br>                name: email_address<br>                type: varchar(255)</pre><pre># Changeset 2 (MIGRATE): backfill, then deploy an app version that<br># reads/writes both columns (or writes both, reads the new one)<br>- changeSet:<br>    id: 011-backfill-email-address<br>    author: ramesh<br>    changes:<br>      - sql:<br>          sql: UPDATE contacts SET email_address = email WHERE email_address IS NULL</pre><pre># Changeset 3 (CONTRACT): once no app version reads `email` anymore<br>- changeSet:<br>    id: 012-drop-email<br>    author: ramesh<br>    changes:<br>      - dropColumn:<br>          tableName: contacts<br>          columnName: email</pre><p>Each step ships in its own deploy, separated by however long it takes to confirm the previous step is safe in production.</p><h3>14. Rollout strategies</h3><p>Rolling deployment is only one rollout strategy.</p><h3>14.1 Recreate deployment</h3><p>Stop the old application and start the new version.</p><p>There can be downtime.</p><h3>14.2 Rolling deployment</h3><p>Replace instances gradually:</p><p>Old and new versions temporarily coexist.</p><h3>14.3 Blue-Green deployment</h3><p>Maintain two complete application environments:</p><p>Initially traffic goes to BLUE; after GREEN is deployed and validated, traffic is switched to GREEN:</p><p>Database compatibility is still important because the two application versions may need to coexist during the transition or rollback.</p><h3>14.4 Canary deployment</h3><p>Send a small portion of traffic to the new version first:</p><p>If the rollout continues successfully, traffic can progressively move toward v2. The percentages above are only an example.</p><h3>14.5 A/B testing</h3><p>Different user groups receive different application behavior:</p><p>A/B testing is primarily about comparing user experiences or behavior rather than simply deploying a new version safely.</p><h3>14.6 Shadow / traffic mirroring</h3><p>A copy of production traffic is sent to the new application, but the new application’s response is not returned to the user:</p><p>This can help test a new version against production-like traffic without making its response authoritative.</p><h3>14.7 Feature flags</h3><p>The application is deployed, but a feature is controlled separately:</p><p>Later, the flag is flipped: New feature → ON. A feature can also be enabled for only a subset of users.</p><h3>14.8 Dark launch</h3><p>New functionality is deployed but hidden from normal users:</p><p>The code can be running in production without exposing the feature through the normal user experience.</p><h3>15. Rollout strategy vs feature exposure</h3><p>These concepts are often mixed together, but they answer different questions.</p><p>They can be combined — for example, <strong>rolling deployment + canary traffic + feature flag</strong> can all be used in the same release.</p><h3>16. Complete production picture</h3><p>Putting everything together:</p><p>During a transition:</p><p>The database engine is responsible for handling concurrent requests and DDL according to its own locking and concurrency mechanisms.</p><h3>17. The four layers to keep separate</h3><h3>One sentence to remember</h3><blockquote><strong><em>CI/CD delivers the application, the rollout strategy controls how application versions receive traffic, Liquibase manages database migrations, and the database engine determines how those migrations actually execute and interact with concurrent requests.</em></strong></blockquote><h3>18. Important correction about “Liquibase runs before Spring Boot”</h3><p>It is useful to draw:</p><p>but this should be understood as a simplified deployment flow, not as a universal physical sequence.</p><p>Depending on the architecture, Liquibase may run:</p><h3>As part of Spring Boot startup</h3><h3>As a separate migration job</h3><p>For larger systems, a separate migration job can provide more explicit control over when migrations happen — and it sidesteps the DATABASECHANGELOGLOCK contention that happens when every instance in a rolling deployment tries to run Liquibase on startup (see next section).</p><h3>19. Liquibase safety mechanisms in production</h3><p>The original walkthrough above covers the conceptual model. These are the concrete Liquibase features that make it safe to use in the scenarios described in §6–§13.</p><h3>DATABASECHANGELOGLOCK and concurrent startups</h3><p>If Liquibase is embedded in the application (§4) and a rolling deployment starts several new instances at once, each instance’s Spring Boot startup tries to run Liquibase. DATABASECHANGELOGLOCK ensures only one of them actually applies changes at a time — the rest wait for the lock, then find there&#39;s nothing left to do (<a href="https://docs.liquibase.com/pro/user-guide-4-33/what-is-the-database-changelog-lock-table">docs.liquibase.com</a>). This is safe, but it means every instance&#39;s startup time now includes a variable wait — a good reason some teams prefer the separate-migration-job model from §18.</p><blockquote><em>If Liquibase (or the process running it) is killed uncleanly, the lock row can be left </em><em>LOCKED = 1, blocking all future updates until it&#39;s cleared manually (</em><em>liquibase release-locks).</em></blockquote><h3>Contexts and labels — controlling what runs where</h3><p>Not every changeset should run in every environment. <strong>Contexts</strong> let a changeset author tag a changeset with an expression, and the person running the deployment decides which contexts are active:</p><pre>&lt;changeSet id=&quot;013-seed-test-data&quot; author=&quot;ramesh&quot; context=&quot;test&quot;&gt;<br>    ...<br>&lt;/changeSet&gt;</pre><pre>liquibase update --contexts=test        # runs it in a test environment<br>liquibase update                        # skips it in production</pre><p><strong>Labels</strong> work similarly but are typically used to group changesets by feature or team rather than environment, and support boolean expressions (--labels=&quot;pro and (shipping or accounts)&quot;). The practical difference: contexts are usually decided by whoever deploys; labels are usually decided by whoever writes the changeset (<a href="https://www.liquibase.com/blog/contexts-vs-labels">liquibase.com</a>).</p><h3>Preconditions — refusing to run an unsafe change</h3><p>A precondition stops a changeset from running unless a condition holds, which is one of the main defenses against exactly the “incompatible schema change” failure in §10’s Case 3:</p><pre>- changeSet:<br>    id: 014-add-not-null-phone<br>    author: ramesh<br>    preConditions:<br>      - onFail: MARK_RAN<br>      - columnExists:<br>          tableName: contacts<br>          columnName: phone<br>    changes:<br>      - addNotNullConstraint:<br>          tableName: contacts<br>          columnName: phone<br>          defaultNullValue: &quot;unknown&quot;</pre><h3>Rollback</h3><p>Every changeset can carry rollback instructions (§2’s rollback: block, or --rollback in SQL format). Given those, you can revert applied changes without hand-writing the inverse SQL each time:</p><pre>liquibase rollback-count --count=1                 # undo the last changeset<br>liquibase rollback-to-date &quot;2026-09-20 00:00:00&quot;    # revert to a point in time<br>liquibase rollback-to-tag v1.4.0                    # revert to a tagged release</pre><p>Rollback undoes <em>schema</em> changes that Liquibase tracked — it is not a substitute for a data backup, and a rollback that drops a column also drops any data that was in it (<a href="https://www.baeldung.com/liquibase-rollback">baeldung.com</a>, <a href="https://docs.liquibase.com/secure/implementation-guide-5-1/implement-a-rollback-strategy-with-sql-changelogs">docs.liquibase.com</a>).</p><h3>20. Practical command reference</h3><p>update-sql in particular is worth adopting as a habit before any production migration: it shows exactly what will run, which is the cheapest way to catch a destructive change (§12) before it reaches the database.</p><h3>21. Final mental model</h3><p>When a new application version requires a database change, think about the process in this order:</p><p>The most important concept:</p><p>They work together, but each has a different responsibility.</p><h3>References</h3><ul><li><a href="https://www.liquibase.org/get-started/core-usage/liquibase-core-concepts-author-database-changes">Liquibase core concepts — author database changes</a></li><li><a href="https://docs.liquibase.com/concepts/changelogs/home.html">What is a changelog?</a></li><li><a href="https://docs.liquibase.com/concepts/changelogs/changeset.html">Changeset overview</a></li><li><a href="https://docs.liquibase.com/concepts/tracking-tables/databasechangelog-table.html">What is the DATABASECHANGELOG table?</a></li><li><a href="https://docs.liquibase.com/pro/user-guide-4-33/what-is-the-database-changelog-lock-table">What is the DATABASECHANGELOGLOCK table?</a></li><li><a href="https://docs.liquibase.com/community/get-started-5-0/install-liquibase-with-spring-boot">Install Liquibase with Spring Boot</a></li><li><a href="https://docs.spring.io/spring-boot/api/java/org/springframework/boot/liquibase/autoconfigure/LiquibaseAutoConfiguration.html">Spring Boot </a><a href="https://docs.spring.io/spring-boot/api/java/org/springframework/boot/liquibase/autoconfigure/LiquibaseAutoConfiguration.html">LiquibaseAutoConfiguration</a></li><li><a href="https://docs.liquibase.com/concepts/changelogs/when-should-i-use-context-and-label-attributes.html">When should I use context and label attributes?</a></li><li><a href="https://www.liquibase.com/blog/contexts-vs-labels">Contexts vs. labels</a></li><li><a href="https://www.liquibase.com/technical-glossary/expand-contract-pattern">What is the expand-contract pattern?</a></li><li><a href="https://docs.liquibase.com/secure/implementation-guide-5-1/implement-a-rollback-strategy-with-sql-changelogs">Implement a rollback strategy with SQL changelogs</a></li><li><a href="https://www.baeldung.com/liquibase-rollback">Introduction to Liquibase Rollback (Baeldung)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47071b524fa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>