<?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 Prashant Kalkar on Medium]]></title>
        <description><![CDATA[Stories by Prashant Kalkar on Medium]]></description>
        <link>https://medium.com/@kalkar.prashant?source=rss-157d975bf065------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fIxsIumwtm6Z_R21.</url>
            <title>Stories by Prashant Kalkar on Medium</title>
            <link>https://medium.com/@kalkar.prashant?source=rss-157d975bf065------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:28:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kalkar.prashant/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[Effective Claude Code patterns]]></title>
            <link>https://medium.com/@kalkar.prashant/effective-claude-code-patterns-7536e4f6ecc9?source=rss-157d975bf065------2</link>
            <guid isPermaLink="false">https://medium.com/p/7536e4f6ecc9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Prashant Kalkar]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 12:01:02 GMT</pubDate>
            <atom:updated>2026-10-22T12:01:02.104Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktnt4vJRQ6qZPSaKnFhBPA.jpeg" /><figcaption>Image generated with Google Gemini</figcaption></figure><p>I have been using Claude Code on a daily basis on a real delivery project. Over time, a lot of patterns emerged that make Claude Code use effective on a project.</p><p>Many of these patterns are already well known or in use by the industry. I am simply borrowing and collecting them here. Industry may use different names for some of these patterns but I have tried using terms that provide more clarity in terms of implementing said pattern. Some of these patterns are directly covered in Claude Certified Architect — Foundations (CCAF) Exam Guide.</p><p>The patterns are not presented in the traditional pattern format but I have found them effective during my use of Claude on projects.</p><p>In sharing these patterns, my hope is to share patterns which I believe will make a large impact in getting value from your Claude code setup.</p><p>Most of the patterns will be useful with any other harness, but I am presenting them specifically for Claude code.</p><p>Let’s dig into the patterns themselves.</p><h3>User Interview Pattern</h3><p>This is one of the most helpful patterns. Software industry for decades has learned that specifying and conveying requirements are hard. It is difficult to specify the requirements which are complete and gap free. Agile manifesto has highlighted the need for customer collaboration. In the age of AI, those customers are, to some extent, us developers.</p><p>Most people do use the <strong>spec driven development</strong> for the use of AI. But I am focusing on more specific way of building that spec. Instead of asking the model to go, analyse and build a spec for a given prompt. It is much more engaging and manageable to build that spec interactively and collaboratively with the model.</p><p>Claude code already ships with a great tool called AskUserQuestion . The tool allows you to answer the requirement questions and even provide direction and alternative answers to ensure Claude Code really understands your intent.</p><p>The interview process allows you to get <strong>engaged</strong> <strong>in decision making</strong>. <strong>Provide relevant context</strong> when required, <strong>highlight environment or organisational constraints</strong>. This is especially useful when you are starting with AI development without much context already captured in repositories.</p><p>Matt Pocock&#39;s skills made this pattern famous with his /grill-me skill. It is also mentioned in the <a href="https://code.claude.com/docs/en/best-practices#let-claude-interview-you">Claude code best practices page</a> and also in the CCAF exam guide.</p><h4>When not to use</h4><p>User interview pattern is best for <strong>medium size tasks </strong>which require some exploration. Tasks that are similar to a story in an epic. Using this pattern for every small, straightforward task will likely increase its <strong>scope and complexity. </strong>Similarly using this pattern for a very big task like building an entire project will likely <strong>ask too many questions</strong> that it will be exhausting. In that case, its first better to break the task into manageable size and use the user interview on the broken tasks.</p><h3>Test-driven development</h3><p>This is one of the technique mentioned in the iterative refinement in the CCAF exam guide. Claude or any coding agent works best when the agent has tight feedback loop. These feedback loops allow agents to quickly recover and ensure they can verify their own work and recover from failure. This reduces the human overhead of checking.</p><p>Here I am using Test-driven development as an umbrella term— any programmatic and deterministic check that provide continuous feedback to the agent ensure high quality work and keep the agent on the right track.</p><p>Other things that come under this technique are linters, checkers, static code analysis tools, mutation testing tools etc.</p><p>One key benefit of this pattern is that it shifts the balance between <strong>work time vs review time </strong>in our favour. Ideally you should be using AI where the work time is huge but it should be small enough to review the work. Any task that is difficult to solve but easy to verify is the best use of the AI. Programmatic checks let us achieve this, at least in some areas.</p><p>This technique though very useful is not error free. Claude can still write wrong or weak tests, write tests which do not really call production code (or call mocked code), can remove tests which it can not make green. To avoid this, human or model oversight is required. See the next pattern for this.</p><p>TDD is a bit special from other checks you may include in this phase (eg. linters or other checkers) — TDD forces the agent to do the <strong>same task from 2 angles </strong>— this generally increases the correctness of the output — this also helps to catch errors. This is similar to <strong>double-entry bookkeeping</strong> in accounting (which is designed to capture errors while entering the data), or asking the password 2 times from the user during change of password.</p><h3>Multi pass independent review</h3><p>This one is taken directly from the CCAF exam guide. For any dev workflow the code or work review phase is very important — this ensure the adherence to the standard laid out by the project, this has to capture any issue in code quality, code architecture, module boundaries etc that can not be captured by the TDD pattern above.</p><p>These model reviews have to solve two issues that are observed in large review passes</p><ol><li><strong>Attention dilution</strong></li><li><strong>Self-review bias</strong>.</li></ol><p>Lets talk about self-review bias. If you ask an agent to review its own work, it is less likely to question its own decisions. This is because the agent has access to its own reasoning tokens which make the agent accept its own choices easily. To avoid this issue — any code review must be done in an <strong>independent agent</strong> (eg. Claude code subagent). That is why the pattern name includes the word ‘<strong>independent’</strong>. The independent review agent, without the earlier reasoning, finds subtle issues better than self-review instructions or extended thinking.</p><p>Another issue is the attention dilution — it is very important to ensure agent does excellent job and ensure to apply coding standard everywhere. It is not good enough to apply the coding agents correct for a few of the early files and then miss same issues in later files. This attention issue is called as <strong>Attention dilution</strong>. To combat the attention dilution use multi-pass review. In pass one, each file is <strong>reviewed independently in separate parallel agents</strong> for any issues. In pass two, a separate <strong>cross-file integration review</strong> looks for structural issues and for issues that span several files. This split also reduces contradictory findings.</p><p>Each review pass (the per-file passes and the cross-file integration pass) can report a confidence score with every finding. You can use the score to route the findings. Send high-confidence findings back to the main agent for fixes. Send low-confidence findings to a human reviewer, who decides if they are worth fixing. Note: a confidence score is only the model’s guess. A model can be very sure and still be wrong. Periodically check the high-score findings for correctness and improve the review prompt if required.</p><h3>Segregate Conditional Context</h3><p>One of the key thing for a context is to ensure correct information exists and is injected at the right time. The opposite should also be true — We should ensure the context (instructions or the data) that are not required are not in the context window.</p><p>Take an example of a code implementation task — if the CLAUDE.md contains the instructions about the SQL queries — those instructions may not be required when working the code implementation work. That instructions required for code task vs instruction required for SQL tasks should be segregated to make them available when they are required.</p><p>Many mechanisms exist to manage this conditional context loading. One mechanism is to use <strong>.claude/rules</strong> with <strong>file glob patterns</strong> to load instructions based on file paths or path extensions. These instructions are brought in only when Claude is dealing with those files.</p><p>Another famous example is the use of skills — which uses progressive disclosure to reduce the context utilisation until the skill is actually required.</p><p>To avoid unnecessary context added in the session — each skill must contain only instructions which are fully applicable when it is loaded. Avoid adding multiple types of instructions in the same skill which are applicable in different scenrios. Loading such a skill will eat up context tokens. If you have such a skill or an agent — either split the skills into multiple distict skills applicable per scenario or change the skill to a routing skill to ask the model to load appropriate skill based on the situation.</p><p>This patterns suggests to move the context away from always loaded context file CLAUDE.md into rule files or skill files — which are loaded only when required.</p><p>One limitation exists however — any such delayed context once loaded, remains in the context window until the session ends. That means along with context segregation, session management is also required.</p><h3>Structured output</h3><p>This is primarily used in agentic systems rather than in the harness for coding agents. Still knowing this pattern is useful. This is naturally being used on coding tasks as you will realise below.</p><p>The biggest impact of the structured output pattern is an <strong>ability to bridge the programmatic world and the natural-language world.</strong></p><p>If all LLM do is generate Natural language output — you will always need LLM/model to validate, review, evaluate that output or you need human to the task.</p><p>But structured output provides ability to consume and process the output programmatically. All kind of programmatic checks and evals can be executed on a structured output.</p><p>As mentioned about in case of coding activities code itself is the structured output allowing all kind of programmatic checks to validate correctness to quality of the generated code.</p><p>Second biggest use of Structured output is the enforcement of a structure on the LLM output (generally this is done through tool schemas but soft enforcement also works for most of the time), this generally enhances the quality of the output. <strong>One trap to avoided</strong> (especially for tool based hard constraints) is cornering LLM into a structure that LLM can not follow for a given situation — eg. missing information, no enum value matches — in this case if not given a sensible way out LLM may hallucinate and fabricate information which does not exist.</p><p>Third use of the structured output is to <strong>capture metadata along with the data</strong>. This helps with auditing, debugging or traceability. For example, you can record where a piece of information came from, or which agent or skill produced an output.</p><p>Eg. In a web research finding capturing from where the information is obtained may be as important as the information itself. Similarly in a multi agent system — finding out which agent produced a given output may be important.</p><h3>Use of subagents judiciously</h3><p>Dev workflows sit on a spectrum. At one end, the user is heavily involved, as in the user interview pattern, where the aim is to discover intent and build shared understanding. At the other end is away-from-keyboard (AFK) work, where the agent works alone and needs no user input.</p><p>The thing is, these separations may not be very clear cut — a workflow may have to jump between deep autonomous work and a need for human input at any time, for example for a key decision.</p><p>The main thing to understand in case of the subagents in Claude Code is they are <strong>single turn</strong> <strong>autonomous agents</strong> having <strong>no way to interact with the user until they complete the work</strong>. So either they have to abandon the work to get user input or they silently decide or just write into plan files that these decisions require user input.</p><p>If the subagents has to be abandon the work — the coordinating agent may not have access to all the reasoning done required for the task.</p><p>Subagents are best for self-contained, independent, procedural and token-heavy tasks, such as <strong>specific research, reviews, gap identification in requirements and prototyping</strong>. The same applies to skills that use context:fork , because they also run in an isolated context. Do not give subagents tasks that need a decision from you.</p><p>Keep any task where you need control and want to keep the decisions in the main agent.</p><p>Note: Technically it is possible to resume the same agent with exact same history. This will resume the work but this is generally time consuming and token heavy. It is better to fix the workflow design rather than using this technical fix.</p><h3>Session aware Workflows</h3><p>When designing any dev workflow, don’t just design the workflow as a set of steps. Also design session boundaries around the workflow steps.</p><p>It should be clear in the workflow steps which steps should be performed in a single session window and which should and could be executed any separate sessions. This allows you to keep token usage under control, keep working in smart zone (avoid issues like “Lost in the Middle” due to too big context)</p><p>This also means you will have to design handoff between workflow steps and ensure nothing is lost between sessions.</p><h3>Retryable Workflow Steps</h3><p>This one I learned by making mistakes in workflow designs in an harness. In a retrospective this seems obvious. This also depends on the realisation that in an AI world throwing away incorrect or low-quality work is sometimes easier than fixing it.</p><p>For this, you need the workflow steps retriable so that you can re-work or re-do only the last step instead of re-doing the whole workflow. But this is only possible if the workflow is designed with this in mind.</p><p>There are 3 things you need for this to work</p><ol><li>Break the workflow into multiple manageable steps</li><li>Keep the steps and their outputs independent so that they can be safely reverted.</li><li>Keep steps independently invocable.</li></ol><p>The first point does not need much explanation. For the second point, it is important to be able to tell the difference between output of the last step vs output of the previous steps. This can also be solved by git commits between the steps, but if this option is not possible then they steps must be designed to ensure previous work is not altered by the next step. The point 3 can be achieved in a Claude code setup by either skills or commands.</p><h3>Guard .claude directory and CLAUDE.md files</h3><p>This pattern goes hand in hand with the next one. It is a good idea to keep control of changes to the .claude directory (containing skills, agents etc) and to the CLAUDE.md files.</p><p>Simplest way is to add ask rules to the project&#39;s .claude/settings.json. This allows LLM to propose changes but you can still control what is accepted. This is even more important now that auto mode has become the default mode in recent versions of Claude Code (v2.1.283 and later).</p><pre>{<br>  &quot;permissions&quot;: {<br>    &quot;ask&quot;: [<br>      &quot;Edit(.claude/**)&quot;,<br>      &quot;Edit(CLAUDE.md)&quot;<br>    ]<br>  }<br>}</pre><h3>Self-critique or self reflection</h3><p>This is a technique, that is used in self learning or self improving agent designs (ref: <a href="https://arxiv.org/pdf/2303.11366">this paper</a>). The idea is to ask the agent to do self reflection or self-critique on failures and ask the agent to propose instruction updates or memory updates from those learnings.</p><p>Generally (as proposed in the paper) the self-reflection is performed after a task fails — but you can also implement as a periodic tasks.</p><p>In our project, we implemented this as a stop hook script. Generally the stop hook will trigger at each end of turn. So added a wrapper script with a counter and trigger the self reflection after every n turns (n = 15 seems to work well). Instead of asking the agent to update instructions we ask it to only propose the changes. That way we can accept or reject the instructions. We have also capped the updates to only top 2 suggestions per reflection.</p><p>The biggest benefit of this technique is continuous validation and improvement of the setup instructions including context capturing.</p><p>That is all for this post.</p><p>There are lot of other patterns which are really useful — which I have not covered here — some of these include effective skill writing, skill evaluations, backlog grooming, Human escalation (or HITL), AFK workflows which can be covered in some other post.</p><p>Do provide your insights or learning in the post comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7536e4f6ecc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rolling deployment with Terraform on AWS]]></title>
            <link>https://medium.com/inspiredbrilliance/rolling-deployment-with-terraform-on-aws-6a0d1587c82c?source=rss-157d975bf065------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a0d1587c82c</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Prashant Kalkar]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 08:12:48 GMT</pubDate>
            <atom:updated>2020-03-16T09:23:34.458Z</atom:updated>
            <content:encoded><![CDATA[<p>Terraform is a great tool to automate your infrastructure provisioning. One of the aims of the automation is having an ability to reproduce the deployments and reducing the time required to do the releases.</p><p>Another important practice is to de-risk the deployment, allowing the teams to deploy continuously even during the working hours.</p><p>This necessitates that the production systems should be continuously available and no downtime window is allowed (like in the old days).</p><p>One of the ways you keep the services available throughout the deployment is to have a rolling deployment strategy.</p><p><em>Rolling deployment can be defined as a deployment when newer instances or resources (like containers) are first added to the infrastructure. The deployment process waits for newer instances to be fulled operational and in service and then only older resources are properly drained and removed.</em></p><h4>Rolling deployment vs Blue-green deployment</h4><p>The point to keep in mind is that rolling deployment is not the same as blue-green deployment.</p><p>In case of successful rolling deployment, you will just have a single service version running in an environment at the end of the deployment. <strong>The decommissioning of the older version is performed as part of the deployment itself.</strong></p><p>In the case of blue-green deployment, the old and new versions of the service are kept running in parallel for some time. Once everything works in the new version in terms of functionality older version is gradually decommissioned. <strong>So decommissioning of the older version is generally a separate step in blue-green deployment. </strong>Blue-green deployment generally gives you an opportunity to test the new version before making it live.<strong> </strong>Also, the old version might be kept running for some time even when a new version is live and serving the traffic.</p><p>Let&#39;s see how a rolling deployment might look like on AWS infrastructure.</p><h4>Rolling deployments on AWS</h4><p>In the context of rolling deployment, we are going to talk about the deployment of a single service. Your overall system might consist of multiple such services, you can extend the same practices to perform rolling deployments for other services in your system.</p><p>Overview of service infrastructure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHXvgSS8ECBspmp4Otkjog.png" /><figcaption>Infrastructure for a service</figcaption></figure><p>Here we are using an ELB (Classic Load balancer), an autoscaling group, a launch configuration, and EC2 instances.</p><p>The load balancer is sending requests to instances in round-robin fashion. In the case of scaling out event auto-scaling group will start EC2 instances as per the launch configuration provided.</p><p>Most of the time, the deployment is required because a new AMI is generated with a newer version of the application.</p><p>In this case, we want our rolling deployment to look like this:</p><ol><li>A new launch configuration will be created.</li><li>A new auto-scaling group will be created which is associated with the new launch configuration.</li><li>The auto-scaling groups will still be associated with the same load balancer (ELB).</li><li>New Auto-scaling will create new instances under the same load balancer. The new instance will use the new launch configuration hence will use the new AMI. These instances are where version 2 of the application is running.</li><li>Once the new instances are in service, old launch configuration, and autoscaling groups will be deleted. Before the deletion of the instances under the autoscaling group, connections from the load balancers will be drained. This allows ongoing requests on older instances to complete.</li></ol><p>Let see how can we do the above with Terraform configuration.</p><h4>Terraform for rolling updates</h4><p>The <strong>full code</strong> is available here: <a href="https://github.com/prashantkalkar/terraform_rolling_deployments">https://github.com/prashantkalkar/terraform_rolling_deployments</a> (Refer to README to run the application).</p><p>We will be using the <strong>Nginx</strong> service as our application. The service will be running on port <strong>80</strong> on the instances.</p><p>Let&#39;s look at the terraform code to create the Autoscaling group and the launch configuration.</p><pre><strong>resource &quot;aws_launch_configuration&quot; &quot;rolling_deployment_launch_config&quot; </strong>{<br>  <strong>name_prefix </strong>= <strong>&quot;rolling_deployment_lc_&quot;<br>  </strong><em>// AMI with nginx installed. Refer nginx.json packer configuration for creating it.<br>  </em><strong>image_id </strong>= <strong>&quot;ami-034836f1b27723260&quot;<br>  instance_type </strong>= <strong>&quot;t3.nano&quot;<br><br>  security_groups </strong>= [aws_security_group.rolling_deployment_instance_sg.<strong>id</strong>]<br><br>  <strong>root_block_device </strong>{<br>    <strong>volume_type </strong>= <strong>&quot;gp2&quot;<br>    volume_size </strong>= <strong>&quot;8&quot;<br>  </strong>}<br><br>  <strong>lifecycle </strong>{<br>    <strong>create_before_destroy </strong>= <strong>true<br>  </strong>}<br>}<br><br><strong>resource &quot;aws_autoscaling_group&quot; &quot;rolling_deployment_asg&quot; </strong>{<br>  <strong>name          </strong>= <strong>&quot;rolling_deployment_asg_${aws_launch_configuration.rolling_deployment_launch_config.name}&quot;<br>  launch_configuration </strong>= aws_launch_configuration.rolling_deployment_launch_config.<strong>name<br>  load_balancers </strong>= [aws_elb.rolling_deployment_elb.<strong>name</strong>]<br>  <strong>availability_zones </strong>= <em>data</em>.<strong>aws_availability_zones</strong>.<strong>zones</strong>.<strong>names<br><br>  min_size             </strong>= 3<br>  <strong>max_size             </strong>= 3<br><br>  <em>// ELB health check should mark the instance as healthy before this time.<br>  </em><strong>health_check_grace_period </strong>= 300<br>  <strong>health_check_type         </strong>= <strong>&quot;ELB&quot;<br><br>  wait_for_capacity_timeout </strong>= <strong>&quot;10m&quot;<br>  wait_for_elb_capacity </strong>= 3 <em>// generally set to ASG desired capacity<br><br>  </em><strong>lifecycle </strong>{<br>    <strong>create_before_destroy </strong>= <strong>true<br>  </strong>}<br>}</pre><h4>Create before destroy</h4><p>Here we have defined a lifecycle for launch configuration (LC) and ASG as <strong>create_before_destroy = true. </strong>As the name suggests this creates the new LC and ASGs before destroying the old one. This ensures that the application keeps serving the requests during the deployment. The new ASG instances will start excepting the requests before we start destroying the old ASG instances.</p><p>Notice another thing is we have used generated names for ASG or LC. For LC, we have just provided a <strong>name_prefix. </strong>Terraform will generate the actual resource name with name_prefix and a randomly generated value.</p><p>Similarly, the name of the ASG depends on the name of the Launch configuration (LC). Since the LC name is generated, the ASG name will also have the generated component.</p><p>Dynamic names are required since we are creating new resources first while the old already exists (<strong>create_before_destoy)</strong>. If you try to use named resources their names will clash with old existing resources. Also making ASG name dependent on LC name ensures that if LC is changed ASG is also recreated ensuring instance creation with new Launch configuration.</p><h4>ASG Healthcheck configuration</h4><p>The next thing to notice is ASG has an <strong>ELB based health check </strong>as follows.</p><pre><em>// ELB health check should mark the instance as healthy before this time.<br>  </em><strong>health_check_grace_period </strong>= 300<br>  <strong>health_check_type         </strong>= <strong>&quot;ELB&quot;</strong></pre><p>The ASG instances once created are by default considered healthy unless marked as unhealthy by the health check mechanism. The health check grace period is the period in which (un)health reporting will be ignored and instances will be assumed to be healthy. The grace period allows the instances to get initialized, the application to start properly and start responding to the health endpoints calls from ELB.</p><p><strong>Ensure, the health check grace period is set to sufficient value to allow application startup.</strong></p><h4>ASG and Load Balancer</h4><p>Also note, that ASG associate itself with the load balancer (ELB).</p><pre><strong>load_balancers </strong>= [aws_elb.rolling_deployment_elb.<strong>name</strong>]</pre><p>The key thing to understand here is, <strong>both old and new ASG instances will be under the load balancer (ELB) at the same time for a short period of time</strong> while old instances are getting drained and newer instances have started serving the requests.</p><h4>Waiting for the load balancer capacity</h4><p>We need to ensure that terraform waits for the new instances to be in service under the ELB before moving on to destroy the old instances.</p><p>Following configuration at ASG ensure just that:</p><pre><strong>wait_for_capacity_timeout </strong>= <strong>&quot;10m&quot;<br>wait_for_elb_capacity </strong>= 3 <em>// generally set to ASG desired capacity</em></pre><p>Here we are saying that Terraform should wait up to 10 mins for the instances to be in service.</p><p>ELB capacity ensures that at least those many instances are services the incoming traffic under the ELB. This can be set to the desired capacity of the ASG.</p><h4><strong>Load balancer health check</strong></h4><p>Lets now look at ELB configuration for the application health check.</p><pre><strong>resource &quot;aws_elb&quot; &quot;rolling_deployment_elb&quot; </strong>{<br>  <strong>name               </strong>= <strong>&quot;rolling-deployment-elb&quot;<br>  availability_zones </strong>= <em>data</em>.<strong>aws_availability_zones</strong>.<strong>zones</strong>.<strong>names<br>  security_groups </strong>= [aws_security_group.rolling_deployment_elb_sg.<strong>id</strong>]<br><br>  <strong>listener </strong>{<br>    <strong>lb_port           </strong>= 80<br>    <strong>lb_protocol       </strong>= <strong>&quot;http&quot;<br>    instance_port     </strong>= 80<br>    <strong>instance_protocol </strong>= <strong>&quot;http&quot;<br>  </strong>}<br><br>  <strong>health_check </strong>{<br>    <strong>healthy_threshold   </strong>= 5<br>    <strong>unhealthy_threshold </strong>= 2<br>    <strong>timeout             </strong>= 5<br>    <strong>target              </strong>= <strong>&quot;HTTP:80/&quot;<br>    interval            </strong>= 30<br>  }<br><br>  <strong>connection_draining         </strong>= <strong>true<br>  connection_draining_timeout </strong>= 300<br>}</pre><p>Here we have defined the ELB with the listener for incoming traffic on port 80 which in-turn forwarded to port 80 where our Nginx is running.</p><p>The interesting part from the rolling deployment point of view is the health check configuration. The ELB will send an HTTP request to every instance on port 80 with path /. If the response from the service endpoint is 200 then the service/application will be considered healthy.</p><p>The health check is done every 30 seconds and the instance is considered healthy for 5 consecutive success responses. So the total process to mark the instance healthy will take at around <strong>150 seconds </strong>once the application has started.</p><p>Make sure, that <strong>health_check_grace_period </strong>at ASG configuration is high enough for the instances to mark as healthy.</p><h4>ELB and connection draining</h4><p>Once the new instances are up and running and serving the traffic. The old instances have to be removed.</p><p>Before removing the instances though, we need to ensure that we provide enough time for the instance to complete requests under service.</p><p>This is achieved by draining configuration at the ELB.</p><pre><strong>connection_draining         </strong>= <strong>true<br>connection_draining_timeout </strong>= 300</pre><p>Once the ASG is marked for deletion by Terraform during the deployment, ELB will <strong>stop sending new requests to old instances</strong> (Note, this will happen once the newer instances are InService). This means that the instances are now in a draining state.</p><p>ELB then wait <strong>draining_timeout</strong> period to allow the application to complete the ongoing requests.</p><p>Once the draining_timeout is over, the instances will be terminated from the ASG and eventually old ASG will be removed as well. This will complete the rolling deployment with a new version of the application running on new instances and old instances terminated.</p><h4>Failures during deployment</h4><p>In case of any failures during the start of the new version of the application, the Terraform process will be terminated with failure. These mean old instances will continue to serve the traffic.</p><p>If the failure occurs, while termination and clean up of old instances then new instances are still servicing the traffic.</p><p>Terraform will mark the <strong>ASG as tainted</strong> in case of the failure and will try to perform the rolling update during the next run.</p><h4>DB Migration Challenges</h4><p>Zero downtime rolling deployments are easy when the new application deployment does not require corresponding changes to DB schemas.</p><p>In the case of DB changes, special considerations are required for zero-downtime deployments. The general idea is to manage the compatibility between DB schema and application versions.</p><p>Details discussion of these techniques is not possible as part of this blog post.</p><h4>Possible drawbacks of this approach</h4><p>The above approach does the rolling deployments while ensuring the application is running throughout the deployment.</p><p>One possible downside of the approach is the re-creation of the ASG for every deployment. If you are capturing the metrics at the ASG level and want to track long terms trends then re-creation of ASG will be a problem.</p><p>This may and may not be a problem in practice, since due to the dynamic nature of the cloud infrastructure and move towards immutable infrastructure you may still prefer to perform deployments by replacing old infrastructure rather than changing in place.</p><h4>Alternative Approaches</h4><p>I have used the following 2 approaches in the past which can be used for rolling deployment.</p><ol><li>Combining Terraform and <strong>CloudFormation</strong> together. CloudFormation provides the rolling deployment capacities for the ASG out of the box. So ASG can be managed with CloudFormation stack. This stack can be created and managed by Terraform.</li><li>Using a <strong>custom script</strong> (python or shell) to perform the rolling deployment. Terraform can be configured to execute the script every time a new launch configuration is created. This can be done with the help of the <strong>provisioner</strong> on the Terraform <strong>null_resource.</strong></li></ol><p>The alternative approaches can be converted as part of the separate blog posts.</p><p>I hope this will help you set up your rolling deployment in the cloud.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a0d1587c82c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inspiredbrilliance/rolling-deployment-with-terraform-on-aws-6a0d1587c82c">Rolling deployment with Terraform on AWS</a> was originally published in <a href="https://medium.com/inspiredbrilliance">inspiringbrilliance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>