<?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 Jude Dsouza on Medium]]></title>
        <description><![CDATA[Stories by Jude Dsouza on Medium]]></description>
        <link>https://medium.com/@dsouza_jude?source=rss-893dbd68b6ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dVkNG321EddKWX6u.</url>
            <title>Stories by Jude Dsouza on Medium</title>
            <link>https://medium.com/@dsouza_jude?source=rss-893dbd68b6ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:37:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dsouza_jude/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[Migrating our PostgreSQL Database of 13 TB to AWS RDS]]></title>
            <link>https://medium.com/@dsouza_jude/migrating-our-postgresql-database-of-13-tb-to-aws-rds-a0d7bc383af4?source=rss-893dbd68b6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0d7bc383af4</guid>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Jude Dsouza]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 11:19:40 GMT</pubDate>
            <atom:updated>2024-12-27T11:19:40.799Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*LnXErkw6wjYZuxOX.png" /><figcaption>Image credits: <a href="https://octopus.com/blog/database-migrations-lessons-learned">Octopus Blog</a></figcaption></figure><p>Over the course of almost 9 years, we at <a href="https://www.zettle.com/">Zettle by PayPal</a> have been self-managing our oldest and largest PostgreSQL database on AWS EC2. This meant doing the equivalent of what AWS RDS offers out of the box, such as</p><ul><li>Taking backups regularly</li><li>Having a well-tested Business Continuity and Disaster Recovery Plan in place. i.e. having a hot standby in place as well as a delayed standby instance in case we need to recover data from an earlier point in time</li><li>Fine tuning for performance and/or scaling up and scaling out. Currently we have 2 read replicas</li><li>Upgrading and patching all the instances mentioned above</li><li>Ensuring there is always enough disk space available and resize if necessary</li><li>Setting up useful metrics and logs</li><li>And on top of that, also ensuring we abide by PCI DSS rules to stay compliant.</li></ul><p>These were tasks we had to do ourselves as you can imagine, it had quite a huge operational burden month after month which took away our focus from doing something rather more exciting, innovative and challenging.</p><p>In this post, I will explain step by step the method and strategy we adopted to migrate all our data to RDS in a reliable and efficient way. Therefore, this post is intended to be technical and is for a technical audience.</p><h3>The Motivation</h3><p>At Zettle, one of our core engineering goals is to achieve <em>Infrastructure Autonomy</em>. Leveraging any kind of managed service, SaaS or PaaS is a step in that direction. At the time, RDS did not exist and hence hosting a PostgreSQL database on EC2 was the only option. Opportunity struck when we were close to hitting the maximum storage limits of what the EBS volume had to offer (i.e. 16 TiB) for the instance type m5d.12xlargewe were using. It was then that we took the decision to migrate all the data over to RDS.</p><h3>The EC2 PostgreSQL Setup</h3><p>Our PostgreSQL database is massive and is a core component of the business. While on EC2, it was on version 13.6 and it had stored approx. 13 TiB of data on an io2 EBS volume provisioned with 12000 IOPS. We used the m5d.12xlarge instance type which has about 48 vCPUs. We had a complete replication chain including a disaster recovery setup in place which can be better explained in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-DjBHzHL2oPu18C_a1aQQ.png" /><figcaption>PostgreSQL DB setup on EC2</figcaption></figure><h3>Migrating to RDS</h3><p>We chose PostgreSQL’s native <a href="https://www.postgresql.org/docs/13/logical-replication.html">logical replication</a> as our method to migrate our data over to RDS. Although it has some <a href="https://www.postgresql.org/docs/13/logical-replication-restrictions.html">limitations</a> which we had to address, but other than that it worked flawlessly.</p><p>On a very high level, following are the steps we took to replicate the data using logical replication. The reasoning for these will be explained in later sections. I will also be using the terms source and publisher interchangeably as well as destination and subscriber to refer to the databases hosted on EC2 and RDS respectively.</p><ol><li>Meet all prerequisite requirements (explained below)</li><li>Import the schema to the RDS instance</li><li>Start the logical replication (i.e. create a PUBLICATION on the source followed by a SUBSCRIPTION on the destination database)</li><li>Wait for all the data to be replicated and in sync and then validate the data</li><li>Fail-over to the RDS instance</li></ol><h4>The Prerequisites</h4><p>For logical replication to succeed, each table needs to have a “<a href="https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-REPLICA-IDENTITY"><em>replica identity</em></a>” so that all UPDATEand DELETEoperations can be replicated. A PRIMARY KEY can be used as a replica identity and therefore as a first step, we needed to ensure all our tables had a primary key. We then used the following query to check for any tables that still did not have a primary key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb2b7eb797be712f4975074e3097d749/href">https://medium.com/media/fb2b7eb797be712f4975074e3097d749/href</a></iframe><p>Next, we created a database replication user at the source that would be used to replicate the data (as you shall see later).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a49491ab1f0101a468a19bf0cb2fc4c/href">https://medium.com/media/6a49491ab1f0101a468a19bf0cb2fc4c/href</a></iframe><p>Next, we allowed for connectivity and replication to the destination database. For this, we needed to add the following configuration to the pg_hba.conf file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fb5258e4a5e863586224227b6a8c71c/href">https://medium.com/media/0fb5258e4a5e863586224227b6a8c71c/href</a></iframe><p>Next, we enabled logical replication and tweaked the following parameters in the postgresq.conf file in order to quickly and efficiently replicate all the data. Note, these values suited the setup we had on EC2 as explained above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8215a1ac1eec76beae6df467f0fa3702/href">https://medium.com/media/8215a1ac1eec76beae6df467f0fa3702/href</a></iframe><p>Restart the PostgreSQL service for the changes to come into effect.</p><pre>&gt;&gt; systemctl restart postgresql-13.service</pre><h4>Importing the Schema to RDS</h4><p>For logical replication to work, the source and the destination databases need to have the <em>same</em> schema so that the logical changes (i.e. INSERTS, UPDATES and DELETES) of a table can be replicated. Therefore, once the replication is in progress, neither the source nor the destination schemas should be altered as it will disrupt the replication for the tables involved.</p><p>To more efficiently replicate the data, it is best to import the schema in two phases, first the roles and the schema itself <em>without</em> the indexes. Then once all the data is replicated and in sync, import all the indexes. Doing it this way speeds up logical replication because it starts with first taking a snapshot of the data on the publisher database and copying that to the subscriber. If the indexes were applied before, it would slow down the snapshot COPY operation thus making it longer for the entire process to complete. This mainly applies to very large tables. The following sections contains an excerpt of the commands I’ve used to achieve this.</p><p><strong>Importing the roles</strong></p><p>For RDS, there is a caveat. We can’t directly import users because a few of them may have the SUPERUSER and/or REPLICATION roles — these are not supported in RDS, so we would need to sanitize them. Once sanitized, we can import them into the destination database. Following is the script that helped me do this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d38417ce5c778d079a3e299c3033436d/href">https://medium.com/media/d38417ce5c778d079a3e299c3033436d/href</a></iframe><p><strong>Importing the schema</strong></p><p>Following is the script I’ve used to dump and import the schema without the indexes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00019a200dbd7fe1c9417fb2af6e003b/href">https://medium.com/media/00019a200dbd7fe1c9417fb2af6e003b/href</a></iframe><p>As you can see from the script, we need to also import the primary keys into the destination database in RDS for the logical replication to succeed. Later, after we start the logical replication and once all the data is replicated and in sync, we can import the indexes.</p><h4>Start the logical replication</h4><p>Once the prerequisites are in place and the schema is imported into the destination database, it should be safe to start the logical replication. It involves creating a <a href="https://www.postgresql.org/docs/13/logical-replication-publication.html">PUBLICATION</a> at the source and a <a href="https://www.postgresql.org/docs/13/logical-replication-subscription.html">SUBSCRIPTION</a> at the destination database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e8e055ac3e357a1aaafb54acc683691/href">https://medium.com/media/2e8e055ac3e357a1aaafb54acc683691/href</a></iframe><p>As described above, you should be able to see the snapshot COPY operation in place with the above ps listing command. It would also be a good idea to check the PostgreSQL logs on both the source and destination to check for errors during the logical replication so it can be fixed.</p><h4>Wait for the data to be in sync and Validate it</h4><p>Once the logical replication has started, we need to monitor its progress and check if all the data has been copied over and on-going writes are continuously replicating.</p><p>In the following query, the lsn_distance_kb is one way to determine the replica lag, in terms of bytes the destination is from the source. This query is to be run on the source database. If the destination database is in sync, then this value will be 0 (or variable close to it if there are still on-going writes to the source database).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22f80ea27ce89a45670f2a46ab5aa6ca/href">https://medium.com/media/22f80ea27ce89a45670f2a46ab5aa6ca/href</a></iframe><p>Additionally, you can monitor progress by checking the <em>state</em> of each replication relation (aka table) in the subscription. The information is available in the <a href="https://www.postgresql.org/docs/13/catalog-pg-subscription-rel.html">pg_subscription_rel</a> catalog and can be determined by the following query. This needs to be run in the subscriber database.</p><p>If all the relations are in the r substate, it means that the initial snapshot is complete, and all tables are ready and normally replicating.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85f0bff3e3c5c4a573aedf2ddf0f6c82/href">https://medium.com/media/85f0bff3e3c5c4a573aedf2ddf0f6c82/href</a></iframe><p>Once all the data is in sync, it should now be safe to apply the indexes as we discussed above. Depending on how large the tables are, this operation can take a very long time and it’s advised to run it in a <a href="https://github.com/tmux/tmux/wiki">tmux</a> session.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3f62accf3e02cdd4e216596f56f8049/href">https://medium.com/media/b3f62accf3e02cdd4e216596f56f8049/href</a></iframe><p>After applying the indexes, we can do a couple of more sanity checks to validate the data. These queries should be run in both the source and destination database and the values should be tallied.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7771ea80ba93107abde046d66d0405a5/href">https://medium.com/media/7771ea80ba93107abde046d66d0405a5/href</a></iframe><p>At this point, it should be all good to fail over to the RDS instance. I will discuss what worked for us and how we managed to do it in a reliable way in the next section.</p><h4>Failing over to RDS</h4><p>In our setup, we had a couple of web services and background jobs we needed to fail over. Fortunately some of these services weren’t that critical, like the admin and back office apps, but others like the monolith app and background jobs were. Also, for scalability reasons, all less critical non-low-latency read-only transactions were done on the read replica EC2 instances. This gave us an opportunity to fail over in steps, starting first with the read replicas, then the less critical apps and finally the critical ones. This way we could test early on for network connectivity, database privileges, data validation and database performance.</p><p>The diagram below visualizes how we planned to fail over the apps from the PostgreSQL DB running on EC2 (dotted blue line) to the RDS instances (green line).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XG1LqM2FOSvn-Kzb-oq_wg.png" /><figcaption>Failing over the apps to RDS (green) from EC2 (blue) PostgreSQL DB</figcaption></figure><p>Before failing over, it was important to run the <a href="https://www.postgresql.org/docs/13/sql-analyze.html">ANALYZE</a> command so that the PostgreSQL’s query engine could generate the best query plan. Optionally one can also run <a href="https://www.postgresql.org/docs/13/sql-vacuum.html">VACUUM ANALYZE</a>, although it’s not necessary as by default PostgreSQL on RDS has <a href="https://www.postgresql.org/docs/13/runtime-config-autovacuum.html">auto vacuuming</a> on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbf89ff2f2d0b53bd6f262a95bbb8e53/href">https://medium.com/media/dbf89ff2f2d0b53bd6f262a95bbb8e53/href</a></iframe><p>Failing over read-only transactions from the EC2 read replicas to the RDS read replicas was quite straightforward. It simply required a configuration change for the new endpoint in the apps followed by a deployment. During this operation there was no downtime. The operation was done a few days before we could fail over all the writes so that we could have some time to validate that everything works as it should and there was no compromise on performance.</p><p>Finally, we proceeded with failing over all the writes, starting with the admin app, which is the least critical. To prevent writes in both the source and destination databases, we had to shutdown all the apps so that data will remain consistent from the viewpoint of all the apps and it will give a chance for on-going writes to get replicated across to the destination so that the value of the lsn_distance_kb (aka replica lag in bytes) in the above query becomes 0. Once all the data was in sync, we shutdown the source database on EC2 and removed all connectivity to it from the apps. This was to guarantee that no writes could ever be made to it and to also prevent any kind of inconsistent state.</p><p>Since sequence data are not replicated due to a <a href="https://www.postgresql.org/docs/13/logical-replication-restrictions.html">limitation</a> of PostgreSQL’s logical replication, before failing over the writes, we needed to update all the sequence data at the destination database. This was easily done via the following query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77eb7a45cb6ccd4d4e276653c8f72e37/href">https://medium.com/media/77eb7a45cb6ccd4d4e276653c8f72e37/href</a></iframe><p>We then updated the configuration of the admin app with the endpoint pointing to the new primary database in RDS and deployed it. After successfully running a couple of manual tests, we proceeded with the monolith app and the background jobs in a similar way and finally we were done with the fail over.</p><p>We observed the performance in <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/monitoring-cloudwatch.html">CloudWatch</a> metrics and RDS <a href="https://aws.amazon.com/rds/performance-insights/">Performance Insights</a> for a few hours and to our expectations, it all looked good. We also monitored the RDS instance PostgreSQL and application logs for any database or application errors respectively but didn’t find anything of concern. With that, we concluded that the migration was completed and successful with a downtime of roughly 30 minutes — but well within the very low traffic hours window — so it did not have quite a negative impact.</p><h4>Cleanup</h4><p>After the migration, we no longer needed the subscription on RDS instance, so we ran the following query to do the necessary cleanup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c44e0d60404c110690473930528d98c/href">https://medium.com/media/4c44e0d60404c110690473930528d98c/href</a></iframe><h3>Results</h3><p>In terms of the database performance between EC2 and RDS, there wasn’t much of a difference between the two as can be noted in the following two graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4PMQPjU-b0q3fXlmcdhfQ.png" /><figcaption>CPU Utilization <strong>EC2 </strong>m5d.12xlarge (before fail over) vs <strong>RDS</strong> db.m6g.12xlarge (after fail over)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LuO8n1IkUZx9sR02aAe7qA.png" /><figcaption>Slow queries &gt; 200 ms <strong>EC2</strong> (before fail over) vs <strong>RDS</strong> (after fail over)</figcaption></figure><h3>Conclusion</h3><p>Myself, not being a database administrator, there was a lot for me to learn from this migration. It was also a great opportunity one that involved such a massive database and which was core to our organization.</p><p>With this migration, we are proud to have taken a huge step forward towards meeting our vision in giving teams the autonomy to manage their own infrastructure, especially when leveraging more and more trusted managed services like <a href="http://aws.amazon.com/">AWS</a> makes this a lot more easier.</p><p>As always, there’s always room for improvement. In retrospect, we could have done a couple of things to minimize the downtime. For instance, we could have applied the sequence data in advance with a greater offset value (in the order of a hundred thousand depending on your use-case) and we could have avoided running some manual tests after we failed-over the less critical apps but rather simply fail-over <em>all</em> the apps at once — this is because PostgreSQL’s logical replication is reliable and battle tested and it just works! And we had already run these tests in our staging environment and they were successful — both of which could have saved us some valuable time. The only thing we imagined that could go wrong was hitting performance bottlenecks on RDS, but we were well prepared for these as well and were ready to scale up the instance in terms of size and IOPS accordingly. I’d love to hear from you if there is something you think we could improve on or could have done differently.</p><p>Lastly, I would like to thank the whole <a href="http://postgresteam.slack.com/">PostgreSQL community</a> and AWS for their support — in particular <a href="https://www.linkedin.com/in/venkiperiyathambi/">Venkatesh Periyathambi</a> and my fellow colleagues here at Zettle, for all the extended help and guidance in helping me and my team perform this database migration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0d7bc383af4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Envoy Proxy’s Traffic Mirroring Functionality]]></title>
            <link>https://medium.com/@dsouza_jude/envoy-proxys-traffic-mirroring-functionality-a54d34c5fbae?source=rss-893dbd68b6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/a54d34c5fbae</guid>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[traffic-shadowing]]></category>
            <category><![CDATA[envoy-proxy]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[traffic-mirroring]]></category>
            <dc:creator><![CDATA[Jude Dsouza]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 11:16:19 GMT</pubDate>
            <atom:updated>2024-12-27T11:16:19.613Z</atom:updated>
            <content:encoded><![CDATA[<p>In a recent project, we faced a use case where we needed to migrate from one system to another. However, rather than directly transitioning to the new system, we wanted a way to test it with live data before releasing it to our internal users. To achieve this, we chose <a href="https://www.envoyproxy.io/">Envoy proxy</a>, specifically leveraging its traffic mirroring functionality.</p><p>Envoy, a high-performance, open-source edge and service proxy, offers a valuable feature known as <strong>traffic mirroring</strong>. This capability enables organizations to replicate live traffic and send it to additional destinations, such as test environments or monitoring systems, without impacting the original service. While it has powerful applications, traffic mirroring also comes with some limitations that must be understood for effective use.</p><h4>What is Traffic Mirroring?</h4><p>Traffic mirroring in Envoy refers to the duplication of live traffic from one service to another. Unlike load balancing, it doesn’t affect the original traffic’s behavior or its destination. Instead, a copy of the traffic is sent to the mirrored destination for testing, monitoring, or debugging purposes.</p><p>For example, you can use mirroring to test a new version of a service with real-world traffic without exposing users to potential issues in the test system.</p><h4>How Does Traffic Mirroring Work?</h4><p>Envoy enables traffic mirroring through its routing configuration. Here’s an overview of the process:</p><ol><li><strong>Define the Primary Route</strong>: The original traffic is routed to its primary destination.</li><li><strong>Set Up a Mirroring Policy</strong>: Rules are defined in the Envoy configuration to duplicate the traffic and send it to a mirrored destination.</li><li><strong>Send Mirrored Traffic</strong>: The duplicated traffic is sent <strong>asynchronously</strong> to the secondary service without altering the original request or response.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12yMJHblGoqsowscqWy5Zg.png" /></figure><p>Here’s an example of a YAML configuration excerpt for traffic mirroring:</p><pre>routes:<br>  - match:<br>      prefix: &quot;/&quot;<br>    route:<br>      cluster: primary-service<br>      request_mirror_policies:<br>        - cluster: mirrored-service</pre><p>This is a very simple configuration that mirrors all the traffic to the “mirrored-service” cluster, however Envoy offers even more advanced functionality such as sending a percentage of the traffic to the mirrored-service. Have a look at the <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#envoy-v3-api-msg-config-route-v3-routeaction-requestmirrorpolicy">spec</a> for more details.</p><h4>Applications of Traffic Mirroring</h4><p>Traffic mirroring has several practical use cases:</p><ol><li><strong>Testing in Production</strong>: Evaluate new services or configurations using real-world traffic without affecting the user experience.</li><li><strong>Performance Benchmarking</strong>: Compare different versions of a service or system under real traffic loads.</li><li><strong>Debugging and Incident Diagnosis</strong>: Replay production traffic to investigate anomalies or incidents in a controlled environment.</li><li><strong>Data Validation</strong>: Ensure a new database or backend system processes live data consistently and accurately.</li><li><strong>Monitoring and Observability</strong>: Capture traffic for in-depth analysis and monitoring.</li></ol><h4>Limitations of Traffic Mirroring</h4><p>While Envoy Proxy’s traffic mirroring is a powerful tool, it does have certain limitations:</p><ol><li><strong>No Response Validation</strong>: Traffic mirroring only duplicates requests, not responses. This means you can observe how the mirrored system processes the traffic, but you cannot compare the responses to ensure correctness.</li><li><strong>Increased Resource Usage</strong>: Mirroring adds network and processing overhead on the proxy, mirrored service, and the network itself. This could lead to resource contention, especially in high-traffic environments.</li><li><strong>Data Sensitivity and Privacy Concerns</strong>: Mirrored traffic might include sensitive user data. It is critical to ensure compliance with data protection regulations and secure handling of the duplicated traffic.</li><li><strong>Asynchronous Nature</strong>: Mirrored requests are sent without waiting for a response. This means you cannot use mirroring for use cases requiring real-time interaction or feedback from the mirrored service.</li><li><strong>Impact on Performance</strong>: Although mirroring does not directly affect the original service, high volumes of mirrored traffic can impact the performance of the Envoy proxy itself, especially if not properly configured or scaled.</li><li><strong>Limited to HTTP/HTTPS</strong>: Envoy’s mirroring functionality is primarily designed for HTTP and HTTPS traffic. Non-HTTP protocols may not be supported in the same way.</li><li><strong>Complexity in Testing Stateful Systems</strong>: Stateful systems often rely on specific sequences of requests or dependencies. Mirrored traffic may not simulate the full state context, leading to incomplete testing.</li></ol><h4>Some Key Considerations and Takeaways</h4><p>To maximize the benefits and minimize the drawbacks of traffic mirroring:</p><ul><li>Monitor and scale your proxy and network resources to handle the additional load.</li><li>Use tools to analyze and validate responses from the mirrored service when applicable.</li><li>Ensure proper data sanitization and encryption for mirrored traffic.</li><li>Test in environments that can handle potential risks without affecting production performance.</li></ul><p>Thank you for taking the time to read this post. I hope you found it insightful and enjoyed learning about Envoy’s traffic mirroring feature. My goal was to share my experiences and the lessons I learned during a recent project, and I sincerely hope I’ve done a good job of conveying them through this post. If you have any thoughts, questions, or feedback, I’d love to hear from you — let’s continue learning together!</p><h4>Useful Links</h4><ul><li><a href="https://www.envoyproxy.io/">Envoy</a>.</li><li><a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#envoy-v3-api-msg-config-route-v3-routeaction-requestmirrorpolicy">Envoy’s Traffic Mirroring spec</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a54d34c5fbae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Observability in a Service Mesh]]></title>
            <link>https://medium.com/paypal-tech/implementing-observability-in-a-service-mesh-273c7409283d?source=rss-893dbd68b6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/273c7409283d</guid>
            <category><![CDATA[consul]]></category>
            <category><![CDATA[service-mesh]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[envoy-proxy]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Jude Dsouza]]></dc:creator>
            <pubDate>Mon, 28 Sep 2020 14:22:24 GMT</pubDate>
            <atom:updated>2021-09-24T19:29:52.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMonk0zLisn9zV5SKce5Tg.jpeg" /><figcaption>A Command-and-Control Center image taken from <a href="https://www.appliedglobal.com/command-control-center-ultimate-guide/">www.appliedglobal.com</a></figcaption></figure><p>I work as an SRE at <a href="https://www.izettle.com/">iZettle</a> and, at times during my on-call, it can be challenging to understand the contributing factors of incidents when they occur or the nature of failures as they happen. As someone running a Microservices Architecture, it’s not an easy task setting up some decent level of observability into the system to quickly understand what’s going on.</p><p>In this article I’d like to share my experiences on how one can improve the observability of services through the use of the <a href="https://www.consul.io/docs/connect">Consul Connect</a> Service Mesh and later I’ll explain my justification for using it compared to other alternatives. Just for a recap, a service mesh allows you to route HTTP traffic through proxies that are deployed as sidecar containers to a service. These proxies can then expose metrics, logs and traces that allow you to gain rich visibility into the system thus making it more efficient to debug applications quickly and easily. Consul Connect, in addition provides service-to-service authorization and encryption using <a href="https://en.wikipedia.org/wiki/Mutual_authentication">mutual TLS</a> and uses <a href="https://www.envoyproxy.io/">Envoy</a> as the data plane for the data transmission. In terms of observability, I will cover basic Layer 7 metrics, access logs and distributed tracing using <a href="https://prometheus.io/">Prometheus</a>, <a href="https://grafana.com/">Grafana</a>, <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html">AWS CloudWatch Logs</a> and <a href="https://aws.amazon.com/xray/">AWS X-Ray</a>.</p><p>All the code for this demo can be found in my <a href="https://github.com/dsouzajude/consul-connect-observability-demo">Github repo</a>.</p><h3>Prerequisites</h3><p>This article will focus mainly on the implementation details, thus the reader is expected to have a basic understanding of Consul’s service mesh feature. If you aren’t already familiar with it you can learn more by following <a href="https://learn.hashicorp.com/tutorials/consul/get-started-service-networking">this guide</a>.</p><h3>The Service Mesh Environment</h3><p>This demo is designed to run on AWS and it uses <a href="https://aws.amazon.com/ecs/">AWS ECS</a> as the Container Orchestration of choice. The following is a diagram that depicts the high level architecture of the Service Mesh implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*SH1fJFUbPkgECUQQj2Nl5g.png" /><figcaption>High level Architecture of the Service Mesh Implementation using Consul Connect running on ECS Fargate</figcaption></figure><p>It comprises of the following:</p><ul><li>A Consul cluster.</li><li>A dashboard and counter service running on AWS ECS Fargate. The dashboard service has an upstream connection with the counter service and communicates <em>securely</em> with it to increment a counter.</li><li>Each of the service’s <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html">Task Definitions</a> has a sidecar container definition for the Envoy Proxy and a Consul agent that communicates with the Consul server.</li><li>A <a href="https://www.consul.io/docs/connect/gateways/ingress-gateway">Consul managed Ingress Gateway</a> for external services to communicate with services inside the mesh.</li></ul><p>Since Consul is the control plane, it is responsible for configuring each of the Envoy proxies. It does this via the same <a href="https://www.consul.io/docs/discovery/services#service-definition">Service Definitions</a> entries that are used to register services into Consul. Following is a example config:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7771ba95ea609b7363db21331172ff47/href">https://medium.com/media/7771ba95ea609b7363db21331172ff47/href</a></iframe><p>Here, the connect.sidecar_service field tells Consul to register a proxy service with default values. For more details on how the sidecar service can be registered read the documentation <a href="https://www.consul.io/docs/connect/registration/sidecar-service">here</a>.</p><p>You can also define global default settings for the proxy via <a href="https://www.consul.io/docs/agent/config-entries/proxy-defaults">proxy-defaults</a> configuration entries. And if that’s not enough, it gives you the flexibility to define more <a href="https://www.consul.io/docs/connect/proxies/envoy#advanced-configuration">advanced</a> and <a href="https://www.consul.io/docs/connect/proxies/envoy#escape-hatch-overrides">custom</a> configurations in the form of <em>Escape Hatches</em>. For a full list of options, check out the Envoy integration page <a href="https://www.consul.io/docs/connect/proxies/envoy">here</a> for more details.</p><p>Throughout the remainder of this article, I will be discussing a couple of these configuration options, in particular, the ones that can help us setup observability so that we can get HTTP Layer7 Metrics, Logs and Tracing.</p><h3>Implementing Observability</h3><p>Envoy is just awesome! It has a comprehensive set of <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/overview/overview">configuration</a> options and has tons of <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/upstream/cluster_manager/cluster_stats#statistics">metrics</a> to share. It is also the component that can give you rich <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/observability/access_log/access_log">access logs</a> and <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v2/config/trace/trace">HTTP Request Tracing</a>. As discussed above, Consul is the control plane through which you can configure Envoy with these options. In this section I will zoom into the implementation details of how this can be done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*6MblySvpuHRVzOfm9-neJQ.png" /><figcaption>Implementing Observability in a Consul Connect Service Mesh using Prometheus, AWS CloudWatch and AWS X-Ray</figcaption></figure><h4>HTTP Layer 7 Metrics</h4><p>In this setup I’ve used Prometheus to scrape metrics from all the sidecar proxies. By setting the <a href="https://www.consul.io/docs/connect/proxies/envoy#envoy_prometheus_bind_addr">envoy_prometheus_bind_addr</a> field in the <a href="https://www.consul.io/docs/connect/proxies/envoy#configuration">proxy.config</a> service definition, Envoy can be configured easily to listen for scrape requests on port 9102.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6ad41d946c6c6dc401cfc7b20b358e5/href">https://medium.com/media/c6ad41d946c6c6dc401cfc7b20b358e5/href</a></iframe><p>Further, Prometheus can discover the proxies automatically using its <a href="https://prometheus.io/docs/prometheus/latest/configuration/configuration/#consul_sd_config">Consul service discovery</a> mechanism as show in the example config below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9c76fec97a77cf84a5c3d24916a7518/href">https://medium.com/media/f9c76fec97a77cf84a5c3d24916a7518/href</a></iframe><p>These metrics can then be visualized in Grafana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMVCrLldDYq-lh4H_UxWvA.png" /><figcaption>Screenshot for Overview of Basic Service Health Layer7 Metrics</figcaption></figure><h4>Access Logs</h4><p><a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/observability/access_log/access_log">Access Logs</a> can also be configured in the Envoy proxy using the <a href="https://www.consul.io/docs/connect/proxies/envoy#escape-hatch-overrides">Escape-Hatch Override</a> option. This option allows you to define a custom <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/listeners/listeners">listener</a> configuration that enables access logging by setting the <a href="https://www.consul.io/docs/connect/proxies/envoy#envoy_public_listener_json">envoy_public_listener_json</a> field as part of the proxy.config definition. You can also define it as part of the <a href="https://www.consul.io/docs/agent/config-entries/proxy-defaults">global proxy-defaults</a> configuration entry as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3cdbfc4135295badd01ff7c9688c8a0/href">https://medium.com/media/a3cdbfc4135295badd01ff7c9688c8a0/href</a></iframe><p>With this config (skipping over the tracing related information which will be covered in the next section), access logs will be written directly to<em> </em>/dev/stdout and automatically collected by AWS CloudWatch Logs driver and pushed into AWS CloudWatch Logs. You should then see logs similar to the following and of-course you can add more fields to it depending on your requirements:</p><pre>{<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;request_id&quot;: &quot;420e2950-50be-43c3-8d41-9b8e9ac9937b&quot;,<br>    &quot;bytes_sent&quot;: &quot;188&quot;,<br>    &quot;origin_path&quot;: &quot;/&quot;,<br>    &quot;authority&quot;: &quot;dashboard.ingress&quot;,<br>    &quot;x_forward_for&quot;: &quot;10.140.21.77&quot;,<br>    &quot;protocol&quot;: &quot;HTTP/1.1&quot;,<br>    &quot;upstream_service_time&quot;: &quot;10&quot;,<br>    &quot;duration&quot;: &quot;10&quot;,<br>    &quot;downstream_remote_addr_without_port&quot;: &quot;10.140.21.77&quot;,<br>    &quot;user_agent&quot;: &quot;curl/7.61.1&quot;,<br>    &quot;upstream&quot;: &quot;127.0.0.1:8080&quot;,<br>    &quot;response_code&quot;: &quot;200&quot;,<br>    &quot;bytes_recv&quot;: &quot;0&quot;,<br>    &quot;response_flags&quot;: &quot;-&quot;,<br>    &quot;start_time&quot;: &quot;2020-09-03T11:47:01.662Z&quot;<br>}</pre><p>The <strong>request_id</strong> field is important here as with this field you can correlate specific traces of request for example in tools like AWS X-Ray and even in Application Logs.</p><h4>HTTP Request Tracing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5ZwxXyi2sw_NKHyabiY8g.png" /><figcaption>An instance of an AWS X-Ray HTTP Trace b/w the Dashboard and Counter service communication</figcaption></figure><p>Finally, HTTP request tracing can be configured in Envoy by setting the <a href="https://www.consul.io/docs/connect/proxies/envoy#envoy_tracing_json">envoy_tracing_json</a> and <a href="https://www.consul.io/docs/connect/proxies/envoy#envoy_extra_static_clusters_json">envoy_extra_static_clusters_json</a> fields of the proxy.config service definition. The former defines the <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v2/config/trace/trace">tracing provider</a>, in my case it’s AWS X-Ray, and the later defines the corresponding static cluster configuration that contains AWS X-Ray’s endpoint so that HTTP request tracing data can be sent to it.</p><p>In order to preserve end-to-end tracing between all services in the service mesh, the services themselves require code that extracts tracing data from the request headers on every inbound connection and forward that on every outbound connection. Additionally, tracing data, in particular the trace_id and request_id must also be included in every log message for traceability and better debugging. With AWS X-Ray, this is possible using their language specific SDK. In the case of Python, you can achieve this using the <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-python.html">aws-xray-sdk</a>. Similarly, there is an SDK for <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-go.html">Go</a>, <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs.html">Node.js</a>, <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-java.html">Java</a>, <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-ruby.html">Ruby</a> and <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-dotnet.html">.NET</a>.</p><h4>Putting it all together</h4><p>For a single service running in AWS ECS, at least 3 sidecar containers are needed for it to be fully integrated into the Consul Service Mesh, these are the Consul Agent, Envoy Proxy and AWS X-Ray daemon. The Dockerfile for each of these can be found in the linked Github repo above. An example list of <a href="https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ContainerDefinition.html">ECS Container Definitions</a> may look like the one below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/322c8d1fa299e343af2b7d80d0b0d6c3/href">https://medium.com/media/322c8d1fa299e343af2b7d80d0b0d6c3/href</a></iframe><p>For simplicity, in this setup, these containers are configured to run on <a href="https://aws.amazon.com/fargate/">AWS ECS Fargate</a> with the <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-networking.html">AWS VPC Task Networking</a> enabled so that all containers get access to the same localhost and can communicate with each other over that interface.</p><ul><li>The first container in the list is the docker image for the application service itself. The service is completely unaware of Consul or the Proxy and is meant to focus only on its own business logic.</li><li>The second is the local Consul Agent which communicates with the Consul Server and is responsible for getting information about other services in the mesh to feed into Envoy for it’s dynamic service discovery. It also provides a way for services to register themselves into Consul.</li><li>The third is the Envoy Proxy which is the dataplane and is responsible for intercepting all inbound and outbound connections between services. In this setup, the container upon initialization, receives the Consul service definition and its related Consul Connect Proxy configuration through the consul_service_config_b64 variable which is encoded in Base64 and registers it into Consul via the local Consul Agent. It then starts the Envoy Proxy.</li><li>Lastly we need distributed tracing on the HTTP level and on the Application Logging level. The amazon/aws-xray-daemon sidecar container helps to achieve this by allowing the application and the Envoy Proxy to send tracing data to it locally over the localhost interface.</li></ul><h3>Conclusion</h3><p>If you’re still reading this, awesome! I hope you’ve enjoyed my walk-through of how one can implement an Observability setup using a Consul Connect Service Mesh. This was my humble attempt to share my experience and I hope you found it useful.</p><p>You might ask why Consul Connect? I think it’s a really great product from Hashicorp and its simplistic design as a control plane makes it a winning factor for my choice of a Service Mesh. This is one of the reasons I chose not to use <a href="https://istio.io/">Istio</a>, also because of its tight coupling with Kubernetes. <a href="https://aws.amazon.com/app-mesh/">AWS AppMesh</a> is also a good and simple alternative but as of this writing, due to its usage of <a href="https://aws.amazon.com/route53/">Route53</a> for Service Discovery which in my experience has resulted in <a href="https://github.com/aws/aws-app-mesh-roadmap/issues/151">delayed DNS propagation</a> and for its limitation around more custom configurations of Envoy, I think Consul Connect has much more to offer so I would still keep a close eye on that and see how things go.</p><p>With regards to AWS CloudWatch Logs, I’ve used it mainly for simplicity but alternatively one can use <a href="https://www.splunk.com/">Splunk</a>, <a href="https://www.sumologic.com/">SumoLogic</a> or the <a href="https://www.elastic.co/webinars/introduction-elk-stack">ELK Stack</a>. On the other hand AWS X-Ray is quite a decent tool for tracing and is simple to setup but because Consul provides a pluggable mechanism for tracing providers, one can use <a href="https://www.jaegertracing.io/">Jaeger</a> as well.</p><p>Lastly, I’m a big fan of Site Reliability Engineering and if you loved reading this post, I’d be happy to hear from you and your recent experiences with implementing and managing a Service Mesh in the comments below. Feel free to connect with me on <a href="https://www.linkedin.com/in/dsouzajude/">LinkedIn</a> as well. Huge shout-out to <a href="https://www.linkedin.com/in/nataliya-remez-52bb093/">Nataliya</a>, <a href="https://uk.linkedin.com/in/davy-jones">Davy</a> and <a href="https://www.linkedin.com/in/krishnapmv/">Krishna</a> for their assistance in proofreading this article.</p><h3>Useful links</h3><ul><li><a href="https://github.com/dsouzajude/consul-connect-observability-demo">Source code on Github</a></li><li><a href="https://www.consul.io/docs">Consul</a>, <a href="https://www.consul.io/docs/connect">Consul Connect,</a> <a href="https://learn.hashicorp.com/tutorials/consul/service-mesh-with-envoy-proxy">Service Mesh Example</a></li><li><a href="https://www.envoyproxy.io/docs/envoy/latest/intro/what_is_envoy">Envoy</a> , <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v2/api">Envoy API v2</a>, <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/life_of_a_request">Life of a Request</a>, <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v2/config/trace/trace">Tracing API</a></li><li><a href="https://aws.amazon.com/xray/">AWS X-Ray</a>, <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-go.html">Go-SDK</a>, <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-python.html">Python-SDK</a></li><li><a href="https://aws.amazon.com/ecs/">AWS ECS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=273c7409283d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/paypal-tech/implementing-observability-in-a-service-mesh-273c7409283d">Implementing Observability in a Service Mesh</a> was originally published in <a href="https://medium.com/paypal-tech">The PayPal Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Logspout as a Fluentd Log Driver Replacement]]></title>
            <link>https://medium.com/magine-engineering/using-fluentd-log-driver-but-still-want-to-debug-your-container-logs-locally-try-logspout-c5b9f6ca9d07?source=rss-893dbd68b6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5b9f6ca9d07</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[fluentd]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[logspout]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Jude Dsouza]]></dc:creator>
            <pubDate>Mon, 15 Jul 2019 15:00:18 GMT</pubDate>
            <atom:updated>2019-07-22T15:31:05.342Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Logspout as a Fluentd Log Driver replacement</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9y6edkw7t5F_1EJqnNJcKg.jpeg" /><figcaption>Beautiful image of logs taken from keremeosreview.com</figcaption></figure><p><strong>TL;DR<br></strong><a href="https://github.com/gliderlabs/logspout">Logspout</a> is a great tool for log routing where as <a href="https://docs.fluentd.org/">Fluentd</a> is a great tool for log processing. However, if you’re using docker’s built-in Fluentd Log Driver, you might have come across a few limitations in the docker-ce edition such as the <a href="https://github.com/moby/moby/issues/34620">log splitting issue</a> and being <a href="https://docs.docker.com/config/containers/logging/configure/">disallowed</a> from viewing your logs locally via <a href="https://docs.docker.com/config/containers/logging/">docker logs</a>. This article explains how to combine the strengths of Logspout and also route your logs directly into Fluentd using a <a href="https://github.com/dsouzajude/logspout-fluentd">custom built</a> Logspout-Fluentd module thus surpassing these limitations and giving you much more control over your logs.</p><h4>What’s Logspout?</h4><p>From the <a href="https://github.com/gliderlabs/logspout#logspout">official documentation</a>:</p><blockquote>Logspout is a log router for Docker containers that runs inside Docker. It attaches to all containers on a host, then routes their logs where you want. It also has an extensible module system.</blockquote><p>The way it attaches itself to containers is by subscribing to docker log events and then routing it to whatever destination you want, in our case to Fluentd. But it’s not all that simple since Logspout doesn’t come with a “built-in” router for Fluentd but because it has an extensible module system, we can write our own module to route logs to Fluentd. In the next section, I will show you how to do exactly that.</p><h4>Extending Logspout with a Fluentd module</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEXEkBdDxNUqO2a7_hRXAg.png" /></figure><p>Logspout has instructions on how to extend itself using custom modules <a href="https://github.com/gliderlabs/logspout/tree/master/custom">here</a>. You can also read up on example custom built extensions <a href="https://github.com/gliderlabs/logspout#third-party-modules">here</a>. I’ve taken a similar but yet up-to-date approach using <a href="https://github.com/golang/go/wiki/Modules">Go 1.11 Modules</a> and a <a href="https://docs.docker.com/develop/develop-images/multistage-build/">Multi-stage</a> build that just includes a custom Logspout binary.</p><p>Based on the instructions, first off, we need to write a simple go module that does the following:</p><ol><li>Register itself to Logspout to receive Docker container log streams</li><li>Process the log streams and forward it to Fluentd</li></ol><p>The code to register the module to Logspout is simple as shown below. We simply define and register a new Fluentd Adapter as the first thing <em>via init() </em>when the package is imported.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53de979052c12a660e7c27bd3e9b3202/href">https://medium.com/media/53de979052c12a660e7c27bd3e9b3202/href</a></iframe><p>Our <em>NewAdapter</em> constructor function should basically construct itself to communicate with Fluentd and send logs to it using the <a href="https://github.com/fluent/fluentd/wiki/Forward-Protocol-Specification-v1">Fluentd protocol specification</a>. The code below uses the <a href="https://github.com/fluent/fluent-logger-golang">fluent-logger-golang/fluent</a> library to do just that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e43fd0e92e7a4eb3059d7b6fe9d17e05/href">https://medium.com/media/e43fd0e92e7a4eb3059d7b6fe9d17e05/href</a></iframe><p>The above code configures the Fluentd adapter to communicate and ingest logs to Fluentd. All that’s left now is to capture the log stream and send it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b141a9ea0470a0035a8e0dac9282c50c/href">https://medium.com/media/b141a9ea0470a0035a8e0dac9282c50c/href</a></iframe><p>Once the adapter logic is ready, we can now include it in our custom Logspout build by following the <a href="https://github.com/gliderlabs/logspout/tree/master/custom">instructions</a> mentioned above. At the very least, we need to include the following:</p><ol><li><strong>modules.go</strong> that will import our adapter into the Logspout binary.</li><li><strong>build.sh</strong> to download Logspout code so that it can be re-built with our custom module.</li><li><strong>Dockerfile</strong> that puts it all together and instructs docker how to build our custom Logspout.</li></ol><p>Steps 1 and 2 are initiated on <a href="https://github.com/gliderlabs/logspout/blob/master/Dockerfile">ONBUILD COPY triggers</a> as soon as we base our image from <em>gliderlabs/logspout:master</em> so we don’t have to explicitly copy it into our Dockerfile.</p><p>Here’s the <em>modules.go</em> that imports our Fluentd adapter logic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d2fe93896584cb71f9741175acefb56/href">https://medium.com/media/2d2fe93896584cb71f9741175acefb56/href</a></iframe><p>And here’s the <em>build.sh</em> file that simply downloads the Logspout source code so it can be custom built.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab73cebdb4aee5cf895ba49e91389480/href">https://medium.com/media/ab73cebdb4aee5cf895ba49e91389480/href</a></iframe><p>And here’s the Dockerfile that does a multi-stage build and uses go 1.11 modules:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41ae2bf1be4763570f64eb666ea88f17/href">https://medium.com/media/41ae2bf1be4763570f64eb666ea88f17/href</a></iframe><p>To build, simply run the following command:</p><pre>&gt;&gt; docker build -t mycustomlogspout .</pre><h4>Using Logspout with our Custom Built Fluentd module</h4><p>After we’ve built Logspout with our custom built Fluentd module, we simply run the docker image with the following command:</p><pre># Example to run custom built logspout locally:</pre><pre>&gt;&gt; docker run --rm --name=&quot;logspout&quot; \<br>       -p 24223:24223 \<br>       -v /var/run/docker.sock:/var/run/docker.sock \<br>       -e TAG_PREFIX=docker \<br>       -e TAG_SUFFIX_LABEL=&quot;com.mycompany.service&quot; \<br>       -e FLUENTD_ASYNC_CONNECT=&quot;true&quot; \<br>       -e PORT=24223 \<br>       -e LOGSPOUT=&quot;ignore&quot; \<br>       mycustomlogspout <br>          ./logspout fluentd://&lt;FLUENTD_IP&gt;:&lt;FLUENTD_PORT&gt;</pre><p>The environment variable TAG_PREFIX will add a fixed tag prefix to every log entry in the stream forwarded to Fluentd. Similarly the TAG_SUFFIX_LABEL environment variable will add a dynamic tag suffix by picking the value from the docker label of your container. Other FLUENTD* specific environment variables relate directly to the fluentd log driver configurations described <a href="https://docs.docker.com/config/containers/logging/fluentd/">here</a>.</p><p>For more environment variables and configurations settings, you can read more on how to use them <a href="https://github.com/dsouzajude/logspout-fluentd#usage">here</a>.</p><p>We can test that logs are actually captured by Logspout and forwarded to Fluentd using a test echo container. The following demonstration uses <a href="https://fluentbit.io/">Fluent-Bit</a> which is a more light-weight version of Fluentd but follows the same protocol specification.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Finnocentyoungbergerpicard&amp;url=https%3A%2F%2Fgfycat.com%2Finnocentyoungbergerpicard&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FInnocentYoungBergerpicard-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1516" height="1004" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad465e7113e77034f5095e03e5045c9f/href">https://medium.com/media/ad465e7113e77034f5095e03e5045c9f/href</a></iframe><h4>Other features of Logspout</h4><p>One nice <a href="https://github.com/gliderlabs/logspout#inspect-log-streams-using-curl">feature</a> of logspout is streaming of all or specific container logs on a host via a REST API. You can simply curl the logspout endpoint and you get nice color coded logs. For this to work, you need to set the PORT=&lt;PORT_NUMBER&gt; environment variable and publish that port on the Logspout container as shown above. Following is the command to see this in action:</p><pre>&gt;&gt; curl localhost:24223/logs</pre><pre>admiring_ishizaka|hello world<br>eloquent_lovelace|hello world<br>   elated_neumann|hello world</pre><h4>Other Notes</h4><ul><li>I was inspired to use Logspout due to a <a href="https://github.com/moby/moby/issues/34620">problem</a> I faced where our application debug logs in JSON were split into smaller chunks when they exceeded 16K bytes. The Fluentd log driver wasn’t yet able to handle this sudden change and neither were any of it’s plugins. Hence it was impossible to construct the logs back to its original form. Using Logspout, this became transparent for our pipeline.</li><li>It might not be trivial to view logs locally or on one of your virtual hosts. Usually you would have a good sophisticated log processing pipeline in place, such as an ELK/EFK stack. In most other cases, ssh-ing into machines to actually view the logs is also not a good idea. So this solution is not intended as a guideline to be included as part of your pipeline, but it doesn’t hurt to have it either. It is however helpful in environments where you need fast debugging and testing for your applications.</li><li>Also note that Logspout will only gather logs from containers that are started without the <em>-t</em> option and that are configured with a logging driver that works with docker logs (journald and json-file).</li></ul><h4>Further reading</h4><p>You can read more on this solution and get the code from my github repo <a href="https://github.com/dsouzajude/logspout-fluentd">@dsouzajude/logspout-fluentd</a>.</p><p>Thank you for reading. Would love to hear your feedback and what you think by commenting below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5b9f6ca9d07" width="1" height="1" alt=""><hr><p><a href="https://medium.com/magine-engineering/using-fluentd-log-driver-but-still-want-to-debug-your-container-logs-locally-try-logspout-c5b9f6ca9d07">Using Logspout as a Fluentd Log Driver Replacement</a> was originally published in <a href="https://medium.com/magine-engineering">Magine Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making it Reliable with 100+ Microservices]]></title>
            <link>https://medium.com/wrapp-tech/making-it-reliable-7d7e69887412?source=rss-893dbd68b6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d7e69887412</guid>
            <category><![CDATA[reliability]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[haproxy]]></category>
            <category><![CDATA[service-discovery]]></category>
            <dc:creator><![CDATA[Jude Dsouza]]></dc:creator>
            <pubDate>Mon, 20 Mar 2017 06:54:23 GMT</pubDate>
            <atom:updated>2017-04-04T20:27:25.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*gyCXUELvc8yU5t7AQ6q_IQ.png" /></figure><p><strong>TL;DR:</strong> Having HAProxy configurations reloaded almost constantly due to dynamic backends is bad and can cause unreliability in the system. However this can be avoided if backend configs are “close-to-static”. The good news is this can be achieved even if you have 100+ microservices at scale.</p><p>If you’ve been working closely with a microservices architecture or are generally interested in the topic, this post is just for you. We at <a href="https://www.wrapp.com/">Wrapp</a> have adopted such an architecture and we host 100+ microservices over 50+ hosts. This post will take you through the reliability challenges we faced with our <a href="https://medium.com/wrapp-tech/on-microservices-and-ecs-wrapp-90665d6c0339#.z8f7okooz">implementation</a> of a microservices architecture and the one we have now transitioned to that helped us produce a more stable, performant and reliable system.</p><p>As discussed in an earlier <a href="https://medium.com/wrapp-tech/on-microservices-and-ecs-wrapp-90665d6c0339#.z8f7okooz">article</a>, our services run inside docker containers and communicate over a REST based HTTP protocol. From our experience, as containers come and go, we observed a lot of unreliability in the system mainly due to the service discovery model we had in place. This model triggered a <a href="http://sirile.github.io/2015/05/18/using-haproxy-and-consul-for-dynamic-service-discovery-on-docker.html">configuration change</a> in HAProxy followed by a reload each time such an event occurred. These events occurred mainly when services were deployed or when hosts were being launched or terminated. Working in a rapidly changing environment where you have frequent deploys throughout the day reloads were bound to occur thereby causing temporary disruptions in how services communicated with each other.</p><p>In this article, my definition of unreliability corresponds to the communication failures between services where they become <em>unavailable</em> to handle requests. In our system, this unavailability takes the form of a HTTP 503 report from our proxy. In such situations we have experienced temporary system failures and sometimes even downtime. To further emphasize my point above, following are two graphs showing the amount of HAProxy reloads on a daily basis from the first part of January and another showing the collective amount of service unavailability in the form of HTTP 503s for the same period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bx7mqhSSObzDgizhx27joA.png" /><figcaption>Figure 1: Number of HAProxy reloads on a daily basis from Jan 01–24, 2017. Averaging ~93K.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeiPSbntoWa0Q2E9Ncy4UA.png" /><figcaption>Figure 2: Collective number of HTTP 503 status codes from all our services on a daily basis from Jan 01–24, 2017. Averaging ~100K.</figcaption></figure><p>Hence from a reliability point of view, this approach to service discovery seemed impractical and unfit for use in our microservice architecture.</p><h3>Improving Service Discovery</h3><p>From the graphs it was evident that at least HAProxy reloads had some correlation with the number of HTTP 503s we’ve seen over time. We also knew that the reloads only happened when there were changes in HAProxy’s configuration so we thought that if these configurations remained the <em>same</em> most of the time it would minimize the amount of reloads and HTTP 503s as well.</p><p><strong>Close to static backend servers</strong></p><p>Keeping the configuration the <em>same</em> would mean to keep the <em>backend servers</em> for a service constant (or close to that). If we included <em>all</em> hosts registered in the cluster for which the service belonged to as backend servers then it would not matter so much when containers of the service were launched or terminated as they would be scheduled over the same set of hosts residing in that cluster. If we configure the health checks the right way, HAProxy would automatically blacklist those servers where the service was not running.</p><p>Thus during deploys to a service, the configuration would remain the same and we should not see any reloads from HAProxy. Following is an example of such a configuration for a service named <em>users</em> that resides in one of the clusters. The scaling factor for this service is 3 (for zone availability) and let’s say there are 5 EC2 instances registered to this cluster. Thus, the configuration for this service would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ea_Se9bM-kejJKXabLrdmw.png" /><figcaption>Figure 3: Sample configuration for users service that includes all EC2 instances as backend servers.</figcaption></figure><p>Note: All our services have a <em>DNS A record</em> that resolves to a local internal IP of the form 192.168.x.x on the host system. This is possible since we have defined these IPs to point to the loopback device on each host. For each service we bind HAProxy to this IP on port 80 so that it becomes easy to communicate to the service such that we only need to make a request to it via its DNS name and not care about it’s port.</p><p>So out of the 5 servers, health checks would fail for 2 of them where the service was not running and would be blacklisted. HAProxy would then only route requests to the remaining healthy servers.</p><p><strong>Centralized HAProxy configurations</strong></p><p>Additionally, by centralizing these configurations to a dedicated cluster of HAProxy hosts, it would further reduce configuration changes for cases where hosts were launched or terminated. The setup would comprise of <em>service</em> hosts and <em>haproxy </em>hosts where the service hosts would only communicate to the HAProxy cluster. Once the request is received by one of the HAProxy host it would forward the request to the relevant backend server. The routing would be done based on the <a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields">Host header</a>. Following are examples of HAProxy configurations for the service and haproxy hosts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pV2UQ0wmt5X-AdZ-i-UMEA.png" /><figcaption>Figure 4: Sample HAProxy configuration for the users service in the <em>service hosts</em>.</figcaption></figure><p>Note: The IPs <em>10.0.10.192</em>, <em>10.0.11.157</em> and <em>10.0.10.135</em> represent the HAProxy hosts and the HAProxy processes running on these hosts listen on port 12121. Any other port number would work too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7_DU_QArpu197T1qvdxgg.png" /><figcaption>Figure 5: Sample HAProxy configuration for the users service in the <em>haproxy hosts</em>.</figcaption></figure><p>Note: The backend servers for the users service would still contain <em>all</em> hosts in the cluster for which the service is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bNU1hy2S6yTT4eq0NCxflw.png" /><figcaption>Figure 6: Wrapp’s Centralized HAProxy setup for inter-service communication.</figcaption></figure><p>Now if any of the service hosts were launched or terminated the configuration would change only in the HAProxy hosts thereby reducing the amount of reloads and disruptions in service-to-service communication.</p><h3>Outcome</h3><p>Following are two graphs in comparison to the ones above showing the amount of HAProxy reloads and service unavailability in the form of HTTP 503s over an extended time period before and after deploying our new service discovery model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1Lc7o6qeNQoDvjc4WjizQ.png" /><figcaption>Figure 7: A significant drop in HAProxy reloads just after deploying the new service discovery model.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsqkxqQ2Hd2po-7PAnGXqQ.png" /><figcaption>Figure 8: Count of HTTP 503s over time w.r.t the old and new service discovery model.</figcaption></figure><p>According to the above graph, during the experimental phase, although our new model showed substantial improvements, after some days we went down partially for about 3 days on Jan 31, Feb 02 and Feb 03. There were seemingly random HTTP 503s from different services and different hosts without any explanation. There was also an unexpected delay in the network traffic for no reason we could think of. We suspected that the HAProxy servers which were running on t2.large instance types were not equipped to handle the load from all the hosts. So we replaced them with 3 c4.xlarge instance types. After recycling them, the problem went away but after a while the very same day we faced the same issue again.</p><p>After hours of debugging, we noticed very random temporary delays in network traffic in some of the hosts and after a while it suddenly went away. We searched a bit on Google for <em>random network delays in c4.xlarge instances</em> and we came across a <a href="https://forums.aws.amazon.com/thread.jspa?messageID=646187">forum</a> stating that the default network driver that was shipped with Ubuntu 14.04 was broken for new instance types such as c4.xlarge or m4.large. It was recommended to upgrade to Ubuntu 16 and install ixgbevf driver version 2.14.2 or above. We had no time for an upgrade as that would probably put in more variables into the equation of random errors. So we thought it was best to switch back to m3.large instance types. After doing so we saw a drop of HTTP 503s compared to what it looked like before.</p><p>The following graph shows how it looked if we excluded those dates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PURh2ZsFRPrSsOIDilw6og.png" /><figcaption>Figure 9: Count of HTTP 503s over time w.r.t the old and new service discovery model excluding dates of network failures.</figcaption></figure><h3>Final thoughts</h3><p>This was fun and we learnt quite a lot in making our system, in particular service discovery, more reliable. We learnt that the effect of large amounts of HAProxy reloads can cause disruptions in service communications. Minimizing it produced a more reliable system. In the article I’ve showed one of the ways to minimize it by having close to static backend server configurations.</p><p>This can be further improved by putting the HAProxy hosts behind an ELB and configuring the service hosts to point to the DNS of the ELB instead of the HAProxy IPs. Then if any of the HAProxy hosts is launched or terminated, it would not trigger a reload of the HAProxy process on the service hosts.</p><p>Although HAProxy is quite good, perhaps it would be better if it could handle more dynamic configurations preferably in memory without having it to reload or restart. Perhaps some proxies like <a href="https://traefik.io/">traefik</a> could do this quite well.</p><p>A few takeaways from this post would be to have good monitoring and visualization tools that can help you answer the following questions — Is there a problem? If so, what is the nature of the problem? Is there a pattern to these problems? What time did it start occurring and on which hosts did it occur? <a href="https://www.sumologic.com/">Sumo Logic</a>, <a href="https://www.librato.com/">Librato</a> and <a href="https://sensuapp.org/">Sensu</a> are some of the tools we’ve used that have helped us greatly in this regard.</p><p>Lastly, keeping the technology stack simple is great. The fewer the dependencies the better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d7e69887412" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wrapp-tech/making-it-reliable-7d7e69887412">Making it Reliable with 100+ Microservices</a> was originally published in <a href="https://medium.com/wrapp-tech">Wrapp Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On Microservices and ECS @ Wrapp]]></title>
            <link>https://medium.com/wrapp-tech/on-microservices-and-ecs-wrapp-90665d6c0339?source=rss-893dbd68b6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/90665d6c0339</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jude Dsouza]]></dc:creator>
            <pubDate>Thu, 14 Jul 2016 11:12:31 GMT</pubDate>
            <atom:updated>2017-03-21T00:05:46.769Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9wrT5J1mbFNjWfIn-XTPQ.png" /></figure><p>This post is about how we run a microservice architecture at Wrapp. I will talk about the challenges associated with it like service orchestration, availability, scalability and service discovery and describe how we solved it. It will also discuss our transition from our own home-built solutions towards AWS EC2 Container service and how it simplified our infrastructure stack. Lastly, I will talk about the challenges that are yet to be solved and how we plan to tackle them.</p><p>At Wrapp, we follow a Microservice architecture and we use Docker container technology to leverage this architecture. We have our entire platform hosted on the Amazon cloud. To this date, we have roughly 90+ services and 50+ EC2 instances. Our original architecture was monolithic until we realized that it was becoming more complex and hence we had to break it out into smaller services and databases accordingly.</p><p><strong>So how did we orchestrate our services?</strong> We decided to cluster our services into two groups. One cluster would host services related to the business itself — we call this the <em>misc </em>cluster. Here we run our user-facing API and other services related to our core business like rewards, notifications, emails and offers. The other cluster would host services related to operations around our infrastructure — we call this the <em>ops</em> cluster. You can expect services like riemann [1], logstash [2], sensu [3] and the like to run here.</p><p>In order to practically do this, we specified what services should run in each cluster via a configuration file in YAML that we called the runlist config. This file also contained details for each service’s configuration e.g the Docker image, version, environment variables, ports and volumes. They were named after their associated cluster and stored in a bucket in S3. The only part missing was the physical stuff — the computing resources where these cluster of services would be hosted. To tie the knot, we defined autoscaling groups, which were a one-to-one mapping to each cluster. So in our example, it meant having a <em>misc-autoscaling</em> and <em>ops-autoscaling</em> group.</p><p>To fit it all together, whenever an instance was launched in an Auto-scaling group, at boot time it would figure out which autoscaling group it belonged to, download the <em>runlist</em> from S3, read the file and finally run Docker containers for the images specified in that file. In addition, we also added each container process to Supervisord [4] to ensure service availability. This way we managed to do service orchestration. The following diagram conceptually explains the end result of our service orchestration procedure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*WneKzBdAdA9SgmpfoMCOMA.png" /><figcaption>Service Orchestration @ Wrapp before ECS</figcaption></figure><p>The way we did <strong>deployments</strong> was via querying Serf [5] to figure out where the service was running, SSH:ing into each such machine, terminating the container and launching a new one from the new image. This was automated by bash scripts. Serf is a cluster tool from Hashicorp [6] that works on a gossip protocol. All our instances were registered into Serf and belonged to one large Serf cluster. A daemon that we built ran on all instances and figured out all containers running on that host. It then uploaded the service name, host IP and protocol for each container into Serf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0xKY7fbcBvuqyj7ZtjiNQ.png" /><figcaption>Service Deployment @ Wrapp before ECS</figcaption></figure><p><strong>Service availability </strong>was done with the help of Supervisord which was basically responsible for ensuring that containers were automatically restarted if they crashed. However we could not <strong>scale</strong> services individually. Instead we had to scale the autoscaling group which in turn launched new instances thus allowing for more services to run in the event of load.</p><p>Lastly, we hosted our own Docker registry backed by S3 and hosted all our Docker images there<strong>.</strong></p><p>All this was good, but not ideal. We had to deal with all this ourselves and of course like any other company we would like to focus more on our business. So along the way came AWS EC2 Container Service (ECS) to the rescue.</p><p>ECS solves a lot of this for us. The following diagram summarizes my thoughts on this and why we felt it was good for our use-case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54dEoxBlwaSy95ceY2wcrA.png" /><figcaption>Transition towards AWS EC2 Container Service</figcaption></figure><p>As you can see, it does all the work for you. The only thing left was service discovery, which we still do ourselves and which is a kind of shortcoming in AWS ECS. The next part of my post will explain how we currently tackle this issue and I will present our proposal for a better and simpler way of addressing it.</p><p><strong>Service discovery</strong> is the backbone of our microservice architecture. Currently at Wrapp, we have incorporated service discovery with the help of tools like Consul [7], Registrator [8] and HAProxy [9].</p><p>Registrator is a tool that runs on all our EC2 instances and its main responsibility is to register all running containers into Consul. It also registers the service’s name, port and protocol along with the instance IP address. Consul aggregates this information across all instances on a service level, hence it knows on what hosts a particular container of a service is running, the protocol it can communicate upon and the port it listens on. All this is vital for service discovery and therefore for services to talk to each other. HAProxy is the bridge that makes the connection between the two services. We used a tool called Consul Template that generates the HAProxy config from the service information in Consul and syncs this config over time. This makes up our service discovery implementation at Wrapp. The following figures explain it visually how it all works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkbsSKHhYWeNw3jgP73ykg.png" /><figcaption>Service Discovery @ Wrapp via Consul, Registrator and HAProxy</figcaption></figure><p>As you can see in the left diagram, we run HAProxy, Registrator and Consul Agent on each of our EC2 instances. Registrator would feed in information to Consul about all services running on the host via the Consul Agent. The diagram on the right is just a zoom-in view of the diagram on the left. It describes how HAProxy’s configuration file is kept up-to-date about all the services running on the host. This is done with the help of Consul Template. An example configuration file is generated in this diagram (just to be a bit clearer) which makes it then possible to communicate with the service.</p><p>I think this approach is too complicated. Consider the following proposal for service discovery via internal (private) AWS Elastic Load Balancers (ELBs) without having Consul or Registrator as part of the solution. This assumes that the EC2 instances run inside a VPC.</p><p>Before you get to the costs, we’ve already thought about it and did the math. If we have around 90 services, that would mean 90+ ELBs and that would be too costly. Of course! But what if we could connect all our services to a single ELB?</p><p>We know that an ELB can be configured with multiple ports. We also know that if traffic ends up on an incoming port, that communication will be forwarded to the port listening on the host, which is attached to the ELB as part of the autoscaling group.</p><p>The ECS API allows your services to be defined in a way so that the service can be associated with an ELB and there is no restriction to associate many services with the same ELB.</p><p>Hence it is practically possible to at least direct traffic onto containers running on a host via the ELB. There are however two issues to this approach. To communicate to a service, you need to know the port at which it listens and secondly, there are no health checks on every port because the ELB only does health checking on a single port. This means when a service is down the ELB will timeout trying to connect to the service and that would cause latency ultimately resulting in a bad user-experience. Instead it would be better if the ELB would return back an HTTP 503. So yes! These are two major drawbacks.</p><p>But we also have a good fix for this! If we put HAProxy before the ELB, it solves all the problems. HAProxy has a way of providing health checks on a service level in its configuration file. This file can be generated via polling the AWS ECS API regularly as it is the source of truth for all our services including information about the ports and protocols they communicates on. The following diagram will hopefully give you a clear idea of what I mean to say:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMel92Lmr4jTK_yTIisUIQ.png" /><figcaption>New proposed way of doing Service Discovery via AWS ELB</figcaption></figure><p>Hence services now don’t need to know about the ports every other service listens on as HAProxy makes this transparent. Using the health checks it completes the missing functionality of the ELB. Thus using a single load balancer and with the help of HAProxy we can implement service discovery for our microservice architecture. At Wrapp, we have developed a small prototype for this and have tested it out — It seemed to work and we are now in the phase of moving it incrementally towards production.</p><p>Stay tuned on our next post to share with you our findings with this approach.</p><p><strong>References:</strong></p><p>[1] Riemann <a href="http://riemann.io/">http://riemann.io/</a></p><p>[2] Logstash <a href="https://www.elastic.co/products/logstash">https://www.elastic.co/products/logstash</a></p><p>[3] Sensu <a href="https://sensuapp.org/">https://sensuapp.org/</a></p><p>[4] Supervisord <a href="http://supervisord.org/">http://supervisord.org/</a></p><p>[5] Serf by HashiCorp <a href="https://www.serfdom.io/">https://www.serfdom.io/</a></p><p>[6] HashiCorp <a href="https://www.hashicorp.com/">https://www.hashicorp.com/</a></p><p>[7] Consul by HashiCorp <a href="https://www.consul.io/">https://www.consul.io/</a></p><p>[8] Registrator <a href="https://github.com/gliderlabs/registrator">https://github.com/gliderlabs/registrator</a></p><p>[9] HAProxy <a href="http://www.haproxy.org/">http://www.haproxy.org/</a></p><p>[10] Consul Template by HashiCorp <a href="https://github.com/hashicorp/consul-template">https://github.com/hashicorp/consul-template</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90665d6c0339" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wrapp-tech/on-microservices-and-ecs-wrapp-90665d6c0339">On Microservices and ECS @ Wrapp</a> was originally published in <a href="https://medium.com/wrapp-tech">Wrapp Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>