<?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[CasaOne Engineering - Medium]]></title>
        <description><![CDATA[Engineering efforts to convert furnitures to utility - Medium]]></description>
        <link>https://medium.com/casaone-engineering?source=rss----79706d24fe1d---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>CasaOne Engineering - Medium</title>
            <link>https://medium.com/casaone-engineering?source=rss----79706d24fe1d---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:08:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/casaone-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Designing Domain Events]]></title>
            <link>https://medium.com/casaone-engineering/designing-domain-events-5efc6e25da52?source=rss----79706d24fe1d---4</link>
            <guid isPermaLink="false">https://medium.com/p/5efc6e25da52</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Deepak Narayana Rao]]></dc:creator>
            <pubDate>Fri, 21 May 2021 09:29:37 GMT</pubDate>
            <atom:updated>2021-05-21T09:31:04.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SkxXfQLV9k50LyGY" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a distributed system, <a href="https://en.wikipedia.org/wiki/Event-driven_architecture">events</a> play a major role in decoupling different components of the system. In this post, we talk about how we improved the design of <a href="https://microservices.io/patterns/data/domain-event.html">domain events</a> to tackle multiple problems in our system.</p><p><strong>Context</strong></p><p><a href="https://www.casaone.com/">CasaOne</a> leasing platform consists of multiple services built around its own <a href="https://martinfowler.com/bliki/BoundedContext.html">bounded context</a>. Last year, we rebuilt a service responsible for managing the leases. We took this opportunity to address some of the issues we had with our earlier design of events.</p><p>We will discuss the following aspects of the service</p><ol><li><strong>Publishing events</strong>: The service should publish an event whenever a notable change occurs to the domain model. Other services in the system should be able to subscribe to these events and react as per business rules. The event should be delivered to consumers <a href="https://www.cloudcomputingpatterns.org/at_least_once_delivery/">at least once</a>.</li><li><strong>Audit trail</strong>: The service should store an audit trail of all the business actions performed in this service.</li></ol><h4>1.1 Publishing events: The past</h4><p>We followed a simple approach in the past. The service published the event directly to the event bus. The business actions in the service performed the following steps in general</p><ul><li>Execute a series of business logic.</li><li>Persist the state of domain entities in the database.</li><li>Publish an event on the event bus (AWS SNS topic in our case).</li></ul><p>For example: when a customer initiates a lease, a “lease” entity is created in the database and an lease.created event is published to the SNS topic.</p><blockquote><strong>Note:</strong> The consumer services have an SQS queue subscribing to the SNS topic. A worker in the consuming service receives the message from the SQS queue and performs the relavant action. For example, a message is queued inassign-stocks-on-lease-created,<em>send-confirmation-email-on-lease-created</em>queues when alease-created event is published.</blockquote><p>The above approach works for most of the cases but it leads to one of the following problems depending on the implementation.</p><ol><li>Phantom event</li><li>Lost event</li></ol><p><strong><em>Implementation 1</em></strong>: As shown in the pseudocode below, the service publishes the event inside the transaction that saves the entity in the database. If the transaction commit fails after the event is published — due to faults such as network issues between service &amp; database or the service crash, it leads to a “<strong>phantom event”</strong> being published to the event bus. The phantom event points to an entity that doesn&#39;t exist in the database.</p><pre>// Example for the phantom event<br>function createLease(lease) {<br>    //...<br>    db.transaction(() =&gt; {<br>        leaseRepository.create(lease);<br>        eventBus.publish({<br>            eventType: &#39;lease.created&#39;,<br>            data: lease<br>        });<br>    });<br>}</pre><p>If such a phantom event is processed by consumers in the above example</p><ul><li>The system will reserve stocks for a non-existing lease. This leads us to spend thousands of dollars on buying new stock and unused stock in the warehouse.</li><li>The customer would be confused about a confirmation email the lease that didn’t go through.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*1PQ1kkcGcT0F2f3Enb6Mbg.png" /><figcaption>Implementation 1: Phantom Event</figcaption></figure><p><strong><em>Implementation 2</em></strong><em>: </em>To overcome the above problem, we can publish the event outside the transaction as shown in the pseudocode below. If publishing the event fails after the DB transaction — due to faults such as network issues between the service &amp; the event bus or the service crash, it leads to a “<strong>lost event”</strong>.</p><pre>// Example for lost event<br>function createLease(lease) {<br>    //...<br>    db.transaction(() =&gt; {<br>        leaseRepository.create(lease);<br>    });</pre><pre>    //Publish the event outside the transaction<br>    eventBus.publish({<br>        eventType: &#39;lease.created&#39;,<br>        data: lease<br>    });<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*jc5-G1C9XLyfJQka9yLo3g.png" /><figcaption>Implementation 2: Lost Event</figcaption></figure><p>The <strong>root cause</strong> of the above issues is — we are performing actions across multiple transactional boundaries i.e the database &amp; the event bus. Ensuring consistency across distributed services would need complex solutions like <a href="https://en.wikipedia.org/wiki/Two-phase_commit_protocol">2-phase commit</a> or <a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/compensating-transaction">compensating transactions</a>. These complex solutions are feasible only if the participating services support them. In many cases, they don’t.</p><p>Let&#39;s look at how we solved this problem by eliminating the need for a transaction across services.</p><h4>1.2 Publishing events: <strong>The Present</strong></h4><p>We came across the <a href="https://microservices.io/patterns/data/transactional-outbox.html">transactional outbox pattern</a> as we started exploring solutions. In this approach,</p><ul><li>The service saves domain entities and the event in the same database within a single transaction.</li><li>An external process will ship the events from the database to the event bus.</li></ul><p>This ensures we will not run into consistency issues between events published and the state of the domain entities. The pseudocode for saving the domain entity and the event is shown below.</p><pre>function createLease(lease) {<br>    //...<br>    db.transaction(() =&gt; {<br>        // Save entity and the event in the same db and transaction<br>        leaseRepository.create(lease);<br>        leaseEventRepository.create({<br>            eventType: &#39;lease.created&#39;,<br>            data: lease<br>        });<br>    });<br>}</pre><p>In our example above, the event is stored in a table called lease_events in the same database. That was the first and the easier part of the problem. We needed a reliable and fast way to ship the events from the events table (transactional outbox) to the event bus. We had the following options:</p><ul><li><strong>Polling publisher: </strong>A background process polls the events table for new events and marks the event as published after publishing the event to the event bus.</li><li><strong>Transaction log tailing: </strong>A background process subscribes to the database transaction logs, filters the logs for changes in the events table, and publishes the event to the event bus. This process maintains the offset of the processed transaction log to know which events have been published to the event bus so far.</li></ul><blockquote><strong>Note</strong>: In both options above, a message can be published to event bus more than once in rare cases such as — when the process publishing the event fails to mark the event as published or fails to update the offset of the late event published. This is expected as per <a href="https://www.cloudcomputingpatterns.org/at_least_once_delivery/">at-least-once</a> delivery semantics. We’ll discuss about how to handle thees duplicate events in the subsequent sections.</blockquote><p>We discussed and debated about the above approaches to arrive at the following conclusion</p><ul><li>The polling publisher approach needed additional tracking data for each event in the events table. And, we would have to choose between — delay in publishing due to infrequent polling or increased load on the DB due to frequent polling.</li><li>The transaction log tailing approach is non-intrusive and allows reuse across multiple services. The mainstream relational DBs provided a way to subscribe to transaction logs using the mechanism they already use for data replication. Due to this, we went with the transaction log trailer approach using <a href="https://debezium.io/"><strong>debezium</strong></a><strong> </strong>which supports <a href="https://debezium.io/blog/2018/07/19/advantages-of-log-based-change-data-capture/"><strong>change data capture(CDC)</strong></a><strong> </strong>from MySQL binlogs.</li></ul><p>A high-level depiction of the solution is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*m0IAnqtop33uMSJI3gnnXw.png" /><figcaption>Transactional Outbox with Transaction Log Trailer</figcaption></figure><blockquote>The above diagram abstracts the intricate details and challenges of shipping events from debezium to the Event Bus we used— AWS SNS. The finer details deserves a separate post by my colleague <a href="https://medium.com/u/5d11315eace9">Ketan Mittal</a> :)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l497yb1ZO7srE1ZM2DwZ8A.png" /><figcaption>Transactional Outbox and CDC Pipeline</figcaption></figure><p>The high-level design decisions we took were</p><ul><li><strong>Backward compatibility for the consumers</strong>: Debezium supported pushing events to Kafka or Kinesis but it doesn’t support SNS. We didn’t want to impose a new consuming pattern for the existing consumers using SQS queues. To support backward compatibility, <em>Debezium</em> pushed events to the Kinesis topic and a lambda function consumed events from the Kinesis topic and published it to a relevant SNS topic.</li><li><strong>Deduplication</strong>: There is a possibility of receiving the same events multiple times from binlogs if debezium fails to update the log offset due to faults. We built an intermediate layer in the pipeline to deduplicate events based on event id.</li><li><strong>Local development support: </strong>We wanted to make sure developers can test publishing and consuming events easily during development. We achieved this using combination of <a href="https://github.com/localstack/localstack">localstack</a> (which we were already using) and scripts to run a minimal version of the above data pipeline.</li></ul><p>The overall solution took us a significant one-time effort initially. But it has yielded us good returns as we onboarded more services with minimal effort as we progressed.</p><p>We had a separate platform team (our data engineering team) focusing on the transaction log tailing component. Our product engineering teams could focus on functional aspects of the service and publish events easily.</p><h4>2.1 Audit trail: The past</h4><p>In the past, we had different tables and APIs for maintaining the history of changes on <a href="https://martinfowler.com/bliki/DDD_Aggregate.html">aggregate root entity</a> and the related entities in the service. Example: status_history , address_history, payment_method_history etc. This approach needed a lot of effort for tracking the history of a new entity or additional information for existing entities.</p><p>This approach was limited by the use of static columns in our transactional database(RDBMS). We wanted to leverage JSON column support in relational DBs to create a generic audit table and generic APIs on top of it to minimize the repeated efforts.</p><p><strong>Eureka!</strong> The events table we created for the transactional outbox had many properties similar to the properties of an audit trail. This allowed us to enrich the events table(the transactional outbox) and use it as an audit trail. This solution is described in the next section (2.2).</p><h4>2.2 Audit trail: The present</h4><p>The transactional outbox for events (the audit trail table) was named as&lt;entity&gt;_events. The high-level structure of this table is as follows</p><ul><li>event_id: A unique identifier for the event.</li><li>event_type: Eg: “lease.created”, “lease.started”.</li><li>schema_version: Eg: “v2”.</li><li>created_at: Event timestamp.</li><li>data: A JSON column containing relevant data for the event.</li><li>&lt;entity&gt;_id: Id of the <a href="https://www.martinfowler.com/bliki/DDD_Aggregate.html">aggregate root</a> entity. This helped in tracking and filtering the events by a specific root entity.</li><li>&lt;related_entity&gt;_id: Optional column(s) for id of related entity(s). This helped in tracking and filtering the events by a related entity.</li></ul><p>We built APIs to allow consumers to get a timeline view of the events across the service. The events could be filtered by the &lt;entity&gt;_id, event_type, time_range, etc. The events could be sorted by recent_first or oldest_first order based on event timestamp.</p><p>This helped us replace multiple history tables with a single audit table as we desired. We could develop additional history/audit trail features in few days instead of a week or more.</p><h4>Summary</h4><p>The above domain event architecture helped us to</p><ul><li>Deliver events to consumers consistently without phantom events and lost events.</li><li>Provided a unified audit trail to track all the actions in the service.</li></ul><p><strong>Conclusion</strong></p><p>In earlier stages of the product, we could simply <a href="https://martinfowler.com/bliki/MonolithFirst.html">start with a monolith</a> architecture to move fast under the time and resource constraints of a startup. As the product and the team started scaling, we had to break the monolith system, and the team into smaller units was to move fast.</p><p>In earlier stages of the breaking monolith to services, a simple-and-naive approach allowed us to move fast and we could handle the one-off errors manually. As we started scaling further, the one-off errors became more expensive and it was necessary to invest time &amp; resources to build a robust solution. This helped us reduce the time spent in managing the errors and spend more time on building useful features for our customers.</p><p>Finally, the solution we choose depends on the scale and the needs during that time. As always, there is no silver bullet.</p><p>We would love to hear about your experience and challenges in designing domain events. Please comment here to share your thoughts and feedback.</p><p><strong>Acknowledgments</strong></p><p>This was a collaborative effort with many of my colleagues at <a href="https://www.casaone.com/">CasaOne</a>. Special credits to <a href="https://medium.com/@teotiashashank">Shashank Teotia</a>, <a href="https://medium.com/u/5d11315eace9">Ketan Mittal</a>, <a href="https://medium.com/u/2f86e5b4dcc7">Ankit Singh</a> for leading the important aspects of the design and implementation.</p><p>If you liked reading this, you might like working with us on challenging problems. We are hiring — click <a href="https://casaone.skillate.com/jobs?department=Technology">here</a> to join us :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5efc6e25da52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/casaone-engineering/designing-domain-events-5efc6e25da52">Designing Domain Events</a> was originally published in <a href="https://medium.com/casaone-engineering">CasaOne Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating from ECS to Kubernetes]]></title>
            <link>https://medium.com/casaone-engineering/migrating-from-ecs-to-kubernetes-189b18235121?source=rss----79706d24fe1d---4</link>
            <guid isPermaLink="false">https://medium.com/p/189b18235121</guid>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Deepak Narayana Rao]]></dc:creator>
            <pubDate>Mon, 17 Aug 2020 14:30:15 GMT</pubDate>
            <atom:updated>2020-08-18T13:35:17.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6LMkQH5FQYy7yxX2" /><figcaption>Photo by <a href="https://unsplash.com/@jbcreate_?utm_source=medium&amp;utm_medium=referral">Joseph Barrientos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We migrated from ECS to Kubernetes (AWS EKS) a few months ago. In this post, we’ll talk about the why, how, the surprises, and our learnings so far. We hope this helps folks exploring Kubernetes or EKS, especially ones who are planning to migrate from ECS.</p><blockquote>This post was not generated by <a href="https://www.theverge.com/2020/8/16/21371049/gpt3-hacker-news-ai-blog">GPT-3</a>, please excuse the typos :)</blockquote><h4>Why did we migrate?</h4><p>We were running our services in AWS ECS for a while since <a href="https://www.casaone.com/">CasaOne</a> started. Our setup had the following problems due to a combination of our tech debt and shortcomings of AWS ECS.</p><ul><li>We were using one cluster per service(eg: orders, inventory, website) initially. This was very inefficient in terms of resource utilization.</li><li>We were using load balancers for internal services as well. There was an opportunity for cost optimization by using internal service discovery and hence reducing the number of load balancers.</li><li>Deploying stateful services wasn’t straight forward in ECS. We were running observability services like Prometheus &amp; ElasticSearch(for APM) using docker-compose on EC2 instances to keep it simple. We needed a platform that has out of the box support for stateful services.</li><li>We had a mix of manual setup &amp; shell scripts from initial days to using <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_service">Terraform</a> for newer services. This was a bit unorganized and inconsistent.</li><li>We had created a lot of internal Terraform modules and tooling for abstracting service deployment. This turned out to be more cognitive load for onboarding new developers due to a lack of documentation and support for these modules. We needed a platform that already has good tooling, knowledge base, and community.</li></ul><p>We needed a bit of an overhaul to fix these issues and scale for the future. We decided to go with <a href="https://kubernetes.io/"><strong>Kubernete</strong></a><strong>s</strong> as our deployment platform - which has become the ubiquitous choice for the container orchestration recently.</p><p>We were also aware of <a href="https://endler.dev/2019/maybe-you-dont-need-kubernetes/">warnings</a> about Kubernetes becoming <a href="https://en.wikipedia.org/wiki/White_elephant">White Elephant</a> for a small team like ours. We kept this mind while choosing the tools and technology for our journey.</p><h4>Planning</h4><p>We started planning this with the following series of decisions on the platform and tools to achieve our goals</p><ul><li><strong>AWS Managed Kubernetes(</strong><a href="https://aws.amazon.com/eks/"><strong>EKS</strong></a><strong>) </strong><em>vs</em> self-managed cluster in AWS using tools like <a href="https://github.com/kubernetes/kops">kops</a>: This was an easier choice considering our team size.</li><li><a href="https://www.terraform.io/"><strong>Terraform</strong></a> <em>vs </em><a href="https://eksctl.io/">eksctl</a> for cluster setup: We chose Terraform in favor of infrastructure as code and based on our earlier experience with Terraform.</li><li><a href="https://github.com/terraform-aws-modules/terraform-aws-eks"><strong>terraform-aws-eks</strong></a> for EKS setup <em>vs</em> writing our own module: This works well with <a href="https://github.com/terraform-aws-modules/terraform-aws-vpc"><strong>terraform-aws-vpc</strong></a> module for VPC setup.</li><li><a href="https://helm.sh/"><strong>Helm</strong></a><strong> </strong><em>vs </em>using kubectl directly.</li><li><a href="https://github.com/kubernetes-sigs/aws-alb-ingress-controller"><strong>aws-alb-ingress-controller</strong></a><strong> </strong><em>vs </em><a href="https://kubernetes.github.io/ingress-nginx/">nginx-ingress-controller</a> for ingress routing: This didn’t work well for us, more details at the end of the post.</li></ul><p>We were all set to try this in our test environment and there was a big <strong><em>surprise</em></strong> waiting for us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGVTkLwfQ14QdJjLPnmktw.png" /></figure><p>This was a huge bummer! After careful deliberation, we decided to move out of the N. California region in AWS. At a high level, we considered access to the latest AWS services, reduced cost, and more Availability Zones for better availability. This decision made our migration more challenging!</p><blockquote>We will skip the nuances of AWS region migration in this post</blockquote><p>We laid down the following points before starting this work</p><ul><li>Migration should have close to zero downtime.</li><li>Migration of the production environment should be done during a low traffic period to reduce any adverse impact on the user experience.</li><li>Migration should be well tested on the testing environment before production.</li></ul><h4>Execution</h4><p>We started with helm charts for low traffic platform services in our test environment. After we gained good confidence in deploying these services, we paired with teams owning other services to write their helm charts and rolled it in our test environment. We observed and fixed issues over a few days.</p><p>We created a playbook for the switchover &amp; rollback and did several runs of this playbook in a test environment. We automated the time-consuming manual steps to ensure this process is fast. After a few weeks of stable application in the testing environment, we came up with the day and time for the production migration and informed relevant stakeholders about this.</p><p>The playbook for switchover included following steps at a high level</p><ul><li>Reduce the TTL for DNS entries pointing to services in ECS cluster</li><li>Deploy services in EKS cluster with cronjobs disabled</li><li>Disable cronjobs in ECS cluster services</li><li>Switch DNS entries to EKS cluster services</li><li>Enable cronjobs in new services</li></ul><p>The playbook for rollback followed similar steps to switch back from service in the EKS cluster to service in the ECS cluster.</p><p>A simplified diagram is shown below</p><figure><img alt="Switchover diagram" src="https://cdn-images-1.medium.com/max/424/1*NyXArm43I0c8WyFWoenQRQ.gif" /><figcaption>Switch over and Rollback representation</figcaption></figure><p>We completed the migration with <strong>~3 minutes</strong> of disruption. The disruption was mainly related to the caching of DNS entries in existing user machines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*WGmoOq6GWnKm4uHgFcdUwA.jpeg" /><figcaption>A high-level view of a deployment environment</figcaption></figure><h4>Issues after the migration</h4><p>Although we pulled off AWS region + EKS migration with minor disruption, few issues surfaced after using it for a while in the production environment</p><ul><li><strong>Intermittent 503 errors after deployment of service</strong>: This was due to an <a href="https://github.com/kubernetes-sigs/aws-alb-ingress-controller/issues/1131">issue</a> in <a href="https://github.com/kubernetes-sigs/aws-alb-ingress-controller">aws-alb-ingress-controller</a> which didn&#39;t update the ALB target group with the IP address of new pods and traffic was still being routed to the terminated pod IP addresses. We switched to <a href="https://kubernetes.github.io/ingress-nginx/">nginx-ingress-controller</a> to overcome this issue.</li><li><strong>CPU throttling due to misconfigured resource allocation</strong>: It took us a while to tune requests and limits configuration of containers w.r.t total CPU available in the EKS cluster. Unfortunately, there is no general guideline for this and you’ll have to observe the traffic pattern of your services to get this right. It is a continuous process — observe, alert &amp; fix.</li></ul><h4>Benefits</h4><ul><li>By using service discovery in k8s, the number of load balancers reduced from 14(at that point in time) to 5. We are still able to serve newer services without the need for the additional load balancer.</li><li>The total cost of our EC2 instances reduced by ~20% and allowed us to use larger EC2 instances with better CPU and networking capabilities.</li><li>We now have a uniform way of deploying all the services. This has increased our infrastructure automation coverage to ~90%.</li><li>Community driven <a href="https://hub.helm.sh/">Helm charts</a> made it very easy to install and configure commonly used OSS services like Prometheus, EFK stack, etc.</li><li>We are making use of k8s <a href="https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/">cronjobs</a> to replace our <a href="https://medium.com/casaone-engineering/how-we-scaled-services-containing-scheduled-tasks-468f12e0b145">earlier approach</a> for scheduled tasks. This helped to reduce the uneven load on web traffic containers.</li><li>Tools like <a href="https://github.com/kubernetes/dashboard">k8s dashboard</a>, <a href="https://github.com/lensapp/lens">lens</a> provide very good visualization of the resources and utilization of the cluster.</li><li>Using namespaces allowed us to logically separate the services of different product stacks within a single cluster.</li></ul><h4>Gotchas &amp; Tips</h4><ul><li>Helm retains only a few releases in history by default. This limits your ability to rollback when there are multiple failed releases. We have set history-max to 100 in helm deploy script to overcome this.</li><li>Helm upgrade --install doesn’t work if the first deploy fails. You will have to delete the failed deployment to overcome this issue.</li><li><a href="https://github.com/jonmosco/kube-ps1">kube-ps1</a> is very useful to add k8s context to shell prompt.</li></ul><h4>Conclusion</h4><p>Compared to a few years ago, Kubernetes has come a long way in terms of documentation(outside GCP), managed service providers, and the tooling that makes it accessible for small teams. Overall, it was a pleasant surprise and experience for us. This exercise also helped us clear a good amount of tech debt in our infrastructure.</p><p>We have only scratched the surface k8s landscape, there is a lot more to explore and learn!</p><h4>Thanks to</h4><ul><li><a href="https://medium.com/u/e6b039275c61">Gaurev Katoch</a> for playing a major role in planning and execution.</li><li><a href="https://medium.com/u/f6df49bbce1f">Madhusudan Kagwad</a> for the review and feedback on this post.</li><li>All our colleagues who are part of this journey.</li></ul><p>PS: We are <a href="https://casaone.skillate.com/jobs?department=Technology">hiring</a>. If you are interested in solving challenging engineering problems like these, join us by applying <a href="https://casaone.skillate.com/jobs?department=Technology">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=189b18235121" width="1" height="1" alt=""><hr><p><a href="https://medium.com/casaone-engineering/migrating-from-ecs-to-kubernetes-189b18235121">Migrating from ECS to Kubernetes</a> was originally published in <a href="https://medium.com/casaone-engineering">CasaOne Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Request log tracing in NodeJS services]]></title>
            <link>https://medium.com/casaone-engineering/request-log-tracing-in-nodejs-services-2941d296a37?source=rss----79706d24fe1d---4</link>
            <guid isPermaLink="false">https://medium.com/p/2941d296a37</guid>
            <category><![CDATA[lcs]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Deepak Narayana Rao]]></dc:creator>
            <pubDate>Thu, 16 Jan 2020 16:08:05 GMT</pubDate>
            <atom:updated>2020-01-16T16:08:05.653Z</atom:updated>
            <content:encoded><![CDATA[<p>by <a href="https://medium.com/u/923c640032d1">Deepak Narayana Rao</a> and <a href="https://medium.com/u/e6b039275c61">Gaurev Katoch</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XMaNf7rBC6VmK_QI" /><figcaption>Photo by <a href="https://unsplash.com/@wehavemegapixels?utm_source=medium&amp;utm_medium=referral">Roman Romashov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As CasaOne started growing, we started breaking our system into multiple services for better organization of our engineering efforts. In this distributed system setup, troubleshooting issues became more challenging as a lot of requests flow through multiple services in the system.</p><p>The ability to trace logs across services became the need of the hour. We divided the problem to build following capabilities in the system</p><ol><li>Aggregated log store to search &amp; view logs</li><li>Ability to correlate logs for a request served by multiple services</li></ol><h4>1. Log Aggregation</h4><p>Our services run as containers in AWS ECS and logs from these containers are stored in CloudWatch log groups. We built a log aggregation pipeline using <a href="https://www.elastic.co/products/beats/functionbeat">functionbeat</a> to push logs from AWS CloudWatch to ElasticSearch, Kibana is used as the frontend for searching and viewing logs.</p><p>This topic itself can be a separate post with more details. We’ll focus more on log correlation in this post.</p><h4>2. Log Correlation</h4><p>Our system predominantly consists of NodeJs services. We wanted to make sure our log correlation implementation is easy to introduce in existing services and scales well for building new services. We laid down the following requirements</p><ul><li>Each service should either receive or generate unique tracing-id per request. This request could be an HTTP request or a message from the Queue</li><li>Each service should add this tracing-id in all log statements</li><li>Each service should add tracing-id to the downstream HTTP requests and the events published to the event bus</li><li>All the above requirements should be achieved using nonobtrusive code</li></ul><p>This is relatively easier to achieve in a platform that uses thread per request model. One would use a ThreadLocal variable to store the tracing-id in request context and make it available for the logging framework to add it in each log statement.</p><p>NodeJS uses a single-threaded event loop with async calls, which made it slightly trickier. But, thanks to <a href="https://github.com/othiym23/node-continuation-local-storage">continuation-local-storage</a> &amp; <a href="https://github.com/jeff-lewis/cls-hooked">cls-hooked</a>, we get a construct similar to ThreadLocal storage to maintain the context across multiple async calls within a single request boundary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*F4u0tPakPtNMiSNdAwO45w.png" /></figure><p>Our implementation of tracing solution shown above has the following touchpoints</p><p>1.<strong> Incoming HTTP requests</strong>: The ExpressJS middleware in the API layer of services generates tracing-id if not present and sets the tracing-id in the context for this request. This trace-id will be available for all statements executed within this request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c97834918cb0a7fe887aaddc93b27edd/href">https://medium.com/media/c97834918cb0a7fe887aaddc93b27edd/href</a></iframe><p>2. <strong>Logger</strong>: The custom log format used in the logger reads the tracing-id from context and adds it to every log statement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecb1558942e2f18ea537e39fce4fb273/href">https://medium.com/media/ecb1558942e2f18ea537e39fce4fb273/href</a></iframe><p>3. <strong>Outgoing HTTP requests: </strong>The HTTP request wrapper library used in all services, passes the tracing-id to the downstream system as an HTTP header. The downstream service also uses the above-mentioned ExpressJS middleware to set CLS context and the custom format for logging</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9d00fb7baa74569bc847a73dc1841a0/href">https://medium.com/media/b9d00fb7baa74569bc847a73dc1841a0/href</a></iframe><p>4. <strong>Outgoing Messages</strong>: The event publisher library(a wrapper for SNS client in our case) used in all services adds the tracing-id as a message attribute in each message published.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd4c268a16616cd44c73b0b3d2d62cbb/href">https://medium.com/media/cd4c268a16616cd44c73b0b3d2d62cbb/href</a></iframe><p>5. <strong>Incoming Messages</strong>: Similar to HTTP request handling, all messages from the queues(SQS) are consumed using a queue consumer wrapper library. Queue consumers using this library read the tracing-id from message attributes and set it in the request context. The logger reads the tracing-id from context and adds it in each log statement as configured above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88dc702a271f52a8ebc75e210db1bd43/href">https://medium.com/media/88dc702a271f52a8ebc75e210db1bd43/href</a></iframe><p>6. <strong>HTTP Response</strong>: The ExpressJS middleware mentioned above adds tracing-id in the response headers as well. This helps client-side applications to log the trace-id or embed it in the error shown to the user (we employ this method in our internal application). This makes it easy to get the trace id for a request or an error.</p><h3>Results</h3><p>This solution has enabled us to debug issues in minutes instead of hours of digging logs across services. Using right tools and libraries, we were able to roll out this solution in short duration and it has proven to be worth the time invested in building this our platform</p><p><em>PS: We are looking for great engineers to join our team and grow with us. Checkout latest jobs </em><a href="https://angel.co/company/casaone/jobs"><em>here</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2941d296a37" width="1" height="1" alt=""><hr><p><a href="https://medium.com/casaone-engineering/request-log-tracing-in-nodejs-services-2941d296a37">Request log tracing in NodeJS services</a> was originally published in <a href="https://medium.com/casaone-engineering">CasaOne Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we scaled services containing scheduled tasks]]></title>
            <link>https://medium.com/casaone-engineering/how-we-scaled-services-containing-scheduled-tasks-468f12e0b145?source=rss----79706d24fe1d---4</link>
            <guid isPermaLink="false">https://medium.com/p/468f12e0b145</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Deepak Narayana Rao]]></dc:creator>
            <pubDate>Wed, 10 Jul 2019 04:56:08 GMT</pubDate>
            <atom:updated>2021-10-01T01:49:28.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJBAiyrqU4RBL4M5gogIGA.png" /></figure><p>CasaOne is a technology-powered contemporary furniture rental company with a mission to deliver the best rental experience to our customers. Our software services run a lot of scheduled tasks periodically in the background to ensure the inventory data is accurate, send email and text notifications to keep the customers informed about the furniture subscription, delivery, pickup, etc.</p><p>During the early days of the startup, we had started with simple in-process cron schedulers to get up and running fast. It looked like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6623a311844839b8be173d1fd3f1712/href">https://medium.com/media/c6623a311844839b8be173d1fd3f1712/href</a></iframe><p>As we started serving more customers and cities, this approach didn’t scale well. We couldn’t run multiple instances of service, as it would have led to undesirable duplicate executions of the tasks. This hampered availability of our services, during peak load and service upgrades</p><p>We had to find a solution to run multiple instances which coordinated to schedule these tasks only once as desired. We couldn’t find any out-of-the-box library for distributed scheduling across multiple instances. Building and managing our own solution for distributed scheduling didn’t seem like the best investment of our time</p><p>We took a step back and started breaking the problem into 2 parts</p><ol><li>Scheduler for triggering the tasks at periodic intervals</li><li>Distributed workers executing tasks from a task queue</li></ol><p>This decomposition simplified it to 2 smaller problems with well-known architecture patterns and solutions. Part 2 of the problem, got reduced to the way we run other background tasks in the system using AWS Simple Queue Service(SQS). For part 1 of the problem, we used AWS CloudWatch rules to publish messages to SQS task queues at periodic intervals.</p><p>The final solution looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*SPhohK-RceLBUlB60sfU6g.png" /></figure><p>We wanted to ensure this solution is easier to work with during development and deployment. Using <a href="https://localstack.cloud/">localstack</a> during development and Terraform for AWS infrastructure automation helped in achieving this goal. As an added benefit, force triggering any of these tasks was as easy as publishing a message to the task queue</p><p>This engineering effort to compose existing solutions saved us from a lot of development effort and helped us provide highly available service to our customers!</p><p><em>We are looking for great engineers to join our team. Checkout latest jobs </em><a href="https://angel.co/company/casaone/jobs"><em>here</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=468f12e0b145" width="1" height="1" alt=""><hr><p><a href="https://medium.com/casaone-engineering/how-we-scaled-services-containing-scheduled-tasks-468f12e0b145">How we scaled services containing scheduled tasks</a> was originally published in <a href="https://medium.com/casaone-engineering">CasaOne Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>