<?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 Slava Markeyev on Medium]]></title>
        <description><![CDATA[Stories by Slava Markeyev on Medium]]></description>
        <link>https://medium.com/@stlava?source=rss-d8db977cf129------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k7LiJTt29KS6pnCnAayIHQ.jpeg</url>
            <title>Stories by Slava Markeyev on Medium</title>
            <link>https://medium.com/@stlava?source=rss-d8db977cf129------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:22:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stlava/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[Scaling Nextdoor’s Datastores: Part 5]]></title>
            <link>https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-5-5221da60f374?source=rss-d8db977cf129------2</link>
            <guid isPermaLink="false">https://medium.com/p/5221da60f374</guid>
            <category><![CDATA[database-consistency]]></category>
            <category><![CDATA[cache-invalidation]]></category>
            <category><![CDATA[database-scalability]]></category>
            <category><![CDATA[caching-strategies]]></category>
            <category><![CDATA[rdbms]]></category>
            <dc:creator><![CDATA[Slava Markeyev]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 15:09:15 GMT</pubDate>
            <atom:updated>2025-03-19T15:18:48.758Z</atom:updated>
            <content:encoded><![CDATA[<p>In this final installment of the Scaling Nextdoor’s Datastores blog series, we detail how the Core-Services team at Nextdoor solved cache consistency challenges as part of a holistic approach to improve our database and cache scalability and usability.</p><p>In <a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-4-c9d3d3edcd34">Part 4: Keeping the cache consistent</a>, we highlighted a class of consistency issues arising from racing cache writes and introduced an approach for forward cache versioning as a mechanism to avoid inconsistencies. The cache is able to decide which write to persist and which to reject because it is aware of the version of data it currently has. However, this is only a partial solution because it assumes writers will always succeed in communicating with the cache in a timely manner, if at all.</p><h3>Missed Writes</h3><p>Let’s consider the scenario where <em>Writers A</em> and <em>B</em> both performed an update to the same row in the database and have not yet updated the cache. <em>Writer A</em> holds <em>Version 1</em> and <em>Writer B</em> holds <em>Version 2</em>. What happens if <em>Writer </em>B with <em>Value 2</em> fails to talk with the cache?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/0*GSlT6qBJGte5Og16" /><figcaption>Writer B fails to write to the cache.</figcaption></figure><p>In this case the result is that the cache becomes inconsistent and we can’t rely on the writers to provide that consistency. A process must exist outside of this interaction to fix-up the cache when Version 2 is written to the database but fails to be written to the cache.</p><h3>Change Data Stream</h3><p>To solve this problem we tap into a common feature provided by most modern databases, a Change Data Capture (CDC) Stream. A CDC Stream is a mechanism to subscribe to row level changes in a database.</p><p>The change stream contains a row’s previous column values along with the new values. Here’s a visual example of the change stream when the <em>last_name</em> field gets updated in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/0*SohlgRgkJIGz8iOy" /></figure><p>For visual clarity the changed values have been underlined in red.</p><h4>Reconciler</h4><p>Since the database is the source of truth and the CDC Stream emits all changes, a consumer of this stream can clean up any consistency issues in the cache. In our system we call this process reconciliation and it’s performed by the ”Reconciler.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*6rg2McNY76b3Gx4y" /></figure><p>The reconciler is responsible for converting CDC change information into input for the <em>del_if_version </em>call to the cache. The arguments for the <em>del_if_version </em>are the version and cache key.</p><p>As discussed in part 4, <em>del_if_version </em>performs conditional deletion of data in the cache (as evaluated by the cache itself) if the supplied version is less than the provided version.</p><blockquote>Author’s Note: Having both old and new column values is particularly important when your cache key is comprised of row values or if you have secondary cache keys for unique column values.</blockquote><p>For the above example the <em>del_if_version </em>function call would have parameters <em>version=2 </em>and <em>key=lastnames:1</em>. The key parameter is made up of two parts, the table name (lastnames) and the primary key for the specific record (row 1).</p><h4>Reconciling Missed Cache Writes</h4><p>Having covered the building blocks, let’s reconsider the case of a missed write. In the below diagram we show that the Reconciler is able to delete <em>Version 1</em> from the cache in the event <em>Writer B </em>does not succeed in updating the cache with <em>Version 2</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/0*Xavx9keXX95S7fGe" /></figure><blockquote>Author’s Note: Astute readers will point out that we could have avoided this issue if the database change stream was used to update the cache. The caveat to this approach is that if you want to keep a look-aside cache design, you then must maintain two different methods of serialization (from ORM objects and from the raw change stream) in sync.</blockquote><h4>Missed Write During Cache Fill</h4><p>Thus far we’ve only discussed writers doing database updates and then updating the cache. However, anytime a reader checks the cache and gets a miss, the reader must populate the cache after fetching from the database.</p><p>The last scenario to consider is what happens when a reader is populating the cache due to a cache miss while a writer is performing a write? Depending on the timing of the sequence of steps the cache may become inconsistent. Consider the following:</p><ol><li>Due to a cache miss the Reader reads <em>Version 1</em> from the database</li><li>The Writer reads <em>Version 1</em> from the database, performs business logic, and writes <em>Version 2</em> to the database</li><li>The Writer fails to write <em>Version 2</em> to the cache</li><li>The Reconciler receives <em>Version 2</em> and deletes <em>Version 1 </em>from the cache</li><li>After some time the Reader re-populates <em>Version 1</em> in the cache</li></ol><p>The end state is the cache has Version 1 and is now inconsistent with the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*U7zXeUgaFU9kJYjw" /></figure><h4>Reconciling Missed Write During Cache Fill</h4><p>The solution to this consistency problem is conceptually simple. The Reconciler must lag behind such that Step 4 in the above diagram happens <em>after </em>Step 5. However, a problem arises in that until the reconciler deletes the stale version in the cache, the cache remains inconsistent.</p><p>For our desired consistency level we wanted to have the Reconciler fix-up the most commonly occurring issues as quickly as possible. In practice missing writes are extremely uncommon for us.</p><p>A simple solution to this problem is having two reconcilers. One instance is reading the change stream and applying fixes to the cache in near real time while another one is <strong>always</strong> a fixed amount of time behind performing any final mopping up. In our case this delay was slightly higher than our web request timeout.</p><blockquote>Author’s Note: There are a handful of other scenarios where a cache inconsistency may occur, but those are fairly complex to articulate. We encourage readers to think through the cases of incomplete and out of order steps. Readers will find that the two-pass reconcilation handles those cases.</blockquote><h3>Reconciliation Pipeline Implementation</h3><p>The discussion about reconciliation has, until now, been theoretical, without addressing the key implementation details and design goals. One functional requirement was to guarantee that users have a cohesive experience, such as seeing their own writes reflected after a page refresh. This meant that reconciliation needed to happen in near real time to provide a seamless experience in the event of a missed cache write.</p><p>The choice to use row versions for conditional deletion of cache keys has a subtle but important consequence: changes do not need to be processed in order. This conscious design choice meant that we could horizontally scale our processing in order to satisfy low latency reconciliation.</p><p>The Reconciler, which we have only discussed conceptually until now, is actually made up of three different pieces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rrt7folsOuBXUVNC" /></figure><h4>Pg-bifrost</h4><p><a href="https://github.com/Nextdoor/pg-bifrost">Pg-bifrost</a>, an open-source tool previously developed by our team, consumes the PostgreSQL WAL Replication log (CDC Stream) and republishes it for use in other applications. It was built with low latency republishing in mind.</p><h4>Apache Kafka</h4><p>Kafka was selected as our persistent message bus for the WAL change stream from the database due to its low latency, persistence guarantees, and well-supported consumer and producer APIs. As Nextdoor was already utilizing Kafka, it was a natural choice for our team.</p><h4>Reconciler</h4><p>The reconciler is simply a GoLang based Kafka consumer that reads the WAL change stream and executes Redis <em>del_if_version</em> calls. The two-pass reconciliation, discussed earlier, was implemented using a time wheel to maintain a fixed offset while remaining relatively straightforward.</p><h3>Putting It All Together</h3><p>This series began by exploring typical relational database scalability issues and the questions teams must consider when addressing them. <a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-2-513922e4b4b1">Part 2 </a>presented an approach to improve read replica usage with semi-intelligent routing. <a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-3-e9b4dd8a9393">Part 3</a> discussed the importance of serializing cached data and its impact on scalability. <a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-4-c9d3d3edcd34">Part 4</a> outlined a cache consistency strategy using row versions and conditional upserts. The final installment, Part 5, highlighted consistency issues and profiled a reconciliation system to maintain database-cache consistency.</p><p>This multifaceted strategy solved the following scalability challenges for our datstores:</p><ul><li>Reduced the load on our primary PostgresSQL databases</li><li>Ensured that only forward versions of database rows were cached for a limited time</li><li>Prevented thundering herds to the cache and databases when database schemas changed</li><li>Made better use of read replicas, which enable effective horizontal scalability for RDBMS</li></ul><h3>Future Work</h3><p>This project was a stepping stone on our database scalability journey. Keen readers likely noticed that our caching system is limited to retrieving items by their primary key or unique attributes. This is due to the fact that key-value storage in a cache is best suited for these types of lookups, and they are essentially an extension of unique database indexes.</p><p>The next step in our database scalability journey is to enable the storage of lists within the cache. This enhancement will allow us to efficiently handle common database queries, such as “<em>Give me a list of people in a neighborhood”</em>.</p><h3>Parting Thoughts From the Authors</h3><p><a href="https://medium.com/u/d8db977cf129">Slava Markeyev</a>: Technologies like no-SQL and new-SQL are often thought of as magic pill solutions to scalability challenges. While they have many advantages over traditional RDBMS solutions, a datastore can fundamentally only be as scalable as the schema and query patterns allow it to be. Changing those two after the fact is akin to rebuilding the engine while the plane is in the air. Doing so is certainly possible — heck, we tried it — but that is a story for another day.</p><p>My parting thought for readers is SQL databases when used in conjunction with secondary indexes like Redis/Valkey for caching and ElasticSearch for search will get you pretty far if you let them.</p><p><a href="https://medium.com/u/e734698562ba">Tushar Singla</a>: While doing architecture interviews, the need often arises to consider how to scale the database to support 100M or even 1B+ users. A common strategy is to “scale out” or add “caching.” Typically, mentioning those concepts are enough to communicate understanding of these horizontally scaling techniques and the interview moves on. However, only after building out this system in real life at scale can one appreciate the intricacies, complexities, and myriad of edge cases that must be handled in order to serve the users appropriately.</p><p>Next time when you mention these techniques during the interview, take some time to consider what it might look like to actually finish the implementation.</p><p><a href="https://medium.com/u/3d01db79be59">Ronak Shah</a>: Scaling a datastore presents unique challenges, and there is no one-size-fits-all solution. Finding the right approach for your system requires thoughtful discussion and a rigorous design process. Although our work was complex and challenging, it was also a truly rewarding experience to be part of.</p><p>P.S. Having robust observability tools and a solid unit testing framework can save countless engineering hours spent debugging cache consistency issues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5221da60f374" width="1" height="1" alt=""><hr><p><a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-5-5221da60f374">Scaling Nextdoor’s Datastores: Part 5</a> was originally published in <a href="https://engblog.nextdoor.com/">Nextdoor Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Nextdoor’s Datastores: Part 1]]></title>
            <link>https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-1-234d0cf67665?source=rss-d8db977cf129------2</link>
            <guid isPermaLink="false">https://medium.com/p/234d0cf67665</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[database-consistency]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[rdbms]]></category>
            <category><![CDATA[database-scalability]]></category>
            <dc:creator><![CDATA[Slava Markeyev]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 15:08:13 GMT</pubDate>
            <atom:updated>2025-03-19T15:21:44.385Z</atom:updated>
            <content:encoded><![CDATA[<p>At Nextdoor, the Core-Services team is responsible for the primary set of databases and caches that power the Nextdoor platform. This blog series explores our 2024 initiatives to enhance the scalability of this critical infrastructure. When we sat down at the whiteboard we sought to address two related problems:</p><ol><li>How can we reduce load on our primary database(s) and better utilize database read replicas?</li><li>How can we improve our cache consistency?</li></ol><p>In this post we’ll provide a primer on the common industry-wide solutions we’ve previously employed along with discussing their caveats and pitfalls. In subsequent posts we’ll dive into the technical details of the components of our solution and how they fit together.</p><h4>Table of Contents</h4><ol><li>Background primer (this post)</li><li><a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-2-513922e4b4b1">Decreasing database load with dynamic routing</a></li><li><a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-3-e9b4dd8a9393">Appropriately serializing data for caching</a></li><li><a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-4-c9d3d3edcd34">Keeping the cache consistent</a></li><li><a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-5-5221da60f374">A time-bounded, eventually-consistent cache</a></li></ol><h3>Background</h3><p>Nextdoor’s backend, built using the Python-based Django web framework, powers the core product experience for neighbors, government agencies, and local businesses. The power of Django and similar frameworks (Rails, Spring, etc) is that they allow development teams to focus on implementing business logic rather than getting caught up in the details like learning and writing SQL.</p><p>The Object Relational Mapping, ORMs, included in these frameworks provide a lever that allows developers to define data models and relationships between them in the application’s language without ever needing to worry about SQL.</p><p>As some readers are all too aware, relational data modeling comes at a cost. Without careful data modeling, performant access to relational data largely depends on that data residing on monolithic databases.</p><p>NoSQL or distributed SQL datastores are often advertised as solutions to the scalability challenges of relational databases like PostgreSQL. However, many companies face significant obstacles in transitioning to these modern datastores. Their relational data models are deeply entrenched, and much of their business logic relies heavily on the power of relational data.</p><p>This was the position the Core-Services team at Nextdoor found ourselves in at the end of 2023. We had explored changing our data model to one that could properly leverage distributed SQL but we ran into existential challenges supporting existing relational queries, specifically multi JOINs, that were scattered across our codebase. Our small team simply could not rewrite business logic to avoid these queries and we couldn’t stop all product development to have other teams do this either.</p><h3>Common solutions</h3><p>Before diving into our most recent solution, it’s worthwhile to discuss how we got to this point. Many platform teams often begin with a basic architecture of the application, via an ORM, talking directly to a relational database like PostgreSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*rwrOyk_w9R7gg90yzfn5MQ.png" /></figure><h3>Caching</h3><p>A ubiquitous pattern that arises in the backend infrastructure lifecycle is adding a cache to take load off of the database. A popular solution, one that Nextdoor employed, was adding a look-aside cache powered by Redis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*iQ7kvT5Cg7WHhqJL" /></figure><p>When using a cache, a few common points of consideration arise:</p><ul><li>You likely want to maintain the flexibility the ORM provides with the benefits of caching. Due to the ORM’s flexibility in querying complex relations, not all queries will be cache-able. What then?</li><li>If performing a read with the intention of doing a write, engineers probably don’t want stale data from the cache. An escape hatch must be built in.</li><li>How do product engineers interact with the cache and database?</li><li>What is actually stored in the cache and how is it formatted? Will the application still be able to read what’s in the cache if the data model / schema changes?</li><li>If the data in the database changes, how does the cache get updated?</li></ul><p>To be clear, not all of these points need to be addressed when initially deploying a cache but they do creep up over time. Like many companies, Nextdoor solved these problems as they started to appear on the horizon. Later parts of this blog series cover components that solve many of these problems, so stay tuned!</p><h3>Read Replicas</h3><p>Another common infrastructure improvement is adding database read replicas to serve queries that can’t be answered by the cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*u_2zAmXUwfj27C_d" /></figure><p>This approach helps address database load on the primary but does not entirely solve the problem. Common issues that arise:</p><ul><li>Engineers may not be able to reason about the various consistency pitfalls that come with this architecture, nor should they if their goal is to simply build product features. If an option is provided, they will choose the perceived safest one: sending their queries to the primary database.</li><li>Business logic will often need to perform some reads followed by a write. This will typically be wrapped in a transaction which will mean this must run on the primary database.</li><li>In order to avoid consistency problems, populating the cache on a cache-miss will likely need to be done by querying the primary database. However, even if the primary database is queried, it does not guarantee that what gets written into the cache is the most up to date version of the data.</li></ul><h3>Data Partitioning</h3><p>Another common solution which teams will employ is splitting up their data across multiple physical databases. This strategy has several different approaches such as splitting by tenancy or breaking up foreign-key relations. Due to our existing data model and access patterns we chose the latter option of severing foreign-key relations such that a set of tables could be moved into their own physical database. While our ORM handled routing to the appropriate database depending on what was being accessed, it did require us to carefully rewrite some business logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*5-Totz_scg2RTLJ7" /></figure><p>This comes along two key caveats:</p><ul><li>This strategy is valid and may be the only option but it only prolongs the runways and does not solve the fundamental problem that a physical database can only be so big.</li><li>Transactions which exist in business logic may now be subtly broken in that they no longer provide atomicity when dealing with successive writes to different databases.</li></ul><p>Teams like ours may eventually find themselves back at square one where the primary database(s) are still a bottleneck and single point of failures despite the efforts to mitigate these problems. Through thoughtful data modeling and incremental work, the problem of database scalability doesn’t have to be immediately existential to businesses. Despite all of the caveats, the above strategies will add years of runways before the problem is well and truly existential.</p><h3>Next Evolution</h3><p>When reevaluating our architecture and system behaviors, we aimed to alleviate the database load issue while also addressing complementary problems discussed in the caveats listed above. Specifically we wanted to:</p><ol><li>Automatically route database queries to read replicas whenever possible.</li><li>Perform cache filling from the database read replicas.</li><li>Provide guaranteed eventual consistency of the cache in a timely manner.</li><li>Allow the application to be able to use what was in the cache even if a developer added a new field/column to a data model.</li></ol><p>Check out <a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-2-513922e4b4b1">the next post in this series</a> on how we employed dynamic routing to shift load from our primary database to the read replicas.</p><p>Authors: <a href="https://medium.com/u/d8db977cf129">Slava Markeyev</a>, <a href="https://medium.com/u/e734698562ba">Tushar Singla</a>, and <a href="https://medium.com/u/3d01db79be59">Ronak Shah</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=234d0cf67665" width="1" height="1" alt=""><hr><p><a href="https://engblog.nextdoor.com/scaling-nextdoors-datastores-part-1-234d0cf67665">Scaling Nextdoor’s Datastores: Part 1</a> was originally published in <a href="https://engblog.nextdoor.com/">Nextdoor Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn DevOps by Doing]]></title>
            <link>https://engblog.nextdoor.com/learn-devops-by-doing-d1e02712d40c?source=rss-d8db977cf129------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1e02712d40c</guid>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[cloud-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Slava Markeyev]]></dc:creator>
            <pubDate>Wed, 23 Feb 2022 17:44:17 GMT</pubDate>
            <atom:updated>2022-02-23T17:44:17.029Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tricky problem and what you can learn from it</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3uSv_qTEc7tpi1W1ikEwRg.jpeg" /></figure><p>Nextdoor’s cloud engineering team moves fast and sometimes it means solving or working around quirky and, often undocumented, problems in vendor services and open source tools. This blog post walks through one of those problems we recently encountered in our infrastructure. While the problem is rather niche, I thought this exercise might be interesting for readers who are less familiar with the problem space, those who might be new to the field of DevOps and are looking to chip away at the question of “<em>what do DevOps engineers do?</em>” In an effort to answer part of this question, I wanted to share a problem we recently came across with validating users in our service mesh. For new readers, the setup to the problem is fairly technical but the crux of it and the solution is actually straight-forward. I hope this account won’t scare you but rather make you excited about diving into problems by keeping the following in mind:</p><blockquote>There’s nothing that you can not learn that can not be learned. There is nothing you can not do that can not be done.</blockquote><h3>Setup and Overall Goal</h3><p>My co-worker came to me with an interesting problem. He set up an AWS Application Load Balancer (ALB) and wanted to use the <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-authenticate-users.html">user authentication feature</a>. This works by the load balancer sending the user through an authentication flow with an identity provider, like Okta or OneLogin, and retrieving information about that user from the identity provider after they have logged in. The information looks something like this:</p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;Slava&quot;,<br>  &quot;email&quot;: &quot;slava@example.com&quot;,<br>  ...<br>}</pre><p>The load balancer then creates a cryptographic signature of this information along with information on which encryption key and hashing algorithm were used during the signing process. This is then stored in the <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-authenticate-users.html#user-claims-encoding"><em>x-amzn-oidc-data</em></a> HTTP request header which gets forwarded along with the original HTTP request from the user to the web application.</p><p>Stepping back for a moment, this authentication flow typically happens in web applications. However, by setting up our infrastructure such that this happens earlier on in the request flow we can standardize the authentication processes and simplify lives of application developers. Anecdotally, this sort of standardization to benefit all developers is a major cornerstone of successful DevOps teams.</p><h4>The Environment</h4><p>As I mentioned, the <em>x-amzn-oidc-data</em> token is typically verified by the downstream application itself but there are reasons to additionally perform the verification earlier on such as layered security, auditing, logging, and routing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*9Mm3_BeDByzSpr5c" /><figcaption>Basic network topology</figcaption></figure><p>In our environment, after the request gets processed by the load balancer it enters our Kubernetes service mesh before being routed to its final destination, a web application. A <a href="https://www.redhat.com/en/topics/microservices/what-is-a-service-mesh">service mesh</a> is an intelligent part of the network infrastructure which dynamically routes requests based on a number of factors to applications. There are a handful of different mesh options available for Kubernetes; our team chose to deploy Istio which is built upon<a href="https://www.envoyproxy.io/"> Envoy</a>. Envoy is a powerful proxying tool initially developed at Lyft and subsequently adopted by the <a href="https://www.cncf.io/about/who-we-are/">Cloud Native Computing Foundation</a>. While at its core Envoy is written in C++, it also allows developers to write scripts in<a href="https://www.lua.org/about.html"> Lua</a> to process HTTP requests.</p><h4>The Data</h4><p>The information in the <em>x-amzn-oidc-data</em> header is written in the <a href="https://jwt.io/introduction">JSON Web Token</a> (JWT) format. The JWT format simply defines how to encode the information about the signer, the user, and the signature itself. The pseudo code looks like:</p><pre>header = {<br>  &quot;alg&quot;: &quot;ES256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;,<br>  &quot;kid&quot;: &quot;1234&quot;,<br>  &quot;signer&quot;: &quot;arn:aws:elasticloadbalancing:us-west-2:1234567890:loadbalancer/app/foobar&quot;<br>}</pre><pre>claims = {<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;Slava&quot;,<br>  &quot;email&quot;: &quot;slava@example.com&quot;<br>}</pre><pre># 1. Encoder claims and header<br>header_enc = base64.encode(header)<br>claims_enc = base64.encode(claims)</pre><pre># 2. Concatenate them together with a period<br>payload = header_enc + &#39;.&#39; + claims_enc</pre><pre># 3. Sign and encode signature<br>sig = crypto.sign(payload, private_key, method=&quot;ES256&quot;)<br>sig_enc = base64.url_encode(sig)</pre><pre># 4. Concatenate signature with the data to form the JWT<br>jwt = payload + &#39;.&#39; + sig_enc</pre><p>In order to <a href="https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm#Signature_verification_algorithm">verify</a> the JWT the application receiving the request needs to go off and lookup the public part of the signing key by its <em>kid</em> (key id) from an endpoint which stores the signing key. Typically, the endpoint to retrieve the key follows the JSON Web Key Set (JWKs) api specification but AWS chose a different approach for making the signing keys available.</p><p>While Envoy already has support for verifying JWT tokens, it only supports the JWKs standard endpoint for retrieving public keys and unfortunately AWS’s endpoint is non-conformant. Luckily with Envoy’s extensibility, we can implement the key fetching and verification ourselves in Lua.</p><h3>A positive attitude</h3><p>By the time I got involved my co-worker had already come up with some Lua code to extract the claim headers, fetch the signing key from an AWS endpoint, and call a signature verification method to verify the claims were signed by the ALB. The only problem was that signature verification kept on failing in a non-obvious manner. Up to this point, my knowledge of JWTs was limited but I had a can-do attitude.</p><p>Solving the signature verification problem proved to be quite challenging. Fairly early on my co-workers identified that the Lua language might not be sufficient enough to solve the problem. This led me down a rabbit hole of writing a signature verification <a href="https://github.com/proxy-wasm/spec/blob/master/docs/WebAssembly-in-Envoy.md">extension</a> for Envoy in TinyGo and subsequently in Typescript after my initial attempt failed. Unfortunately both attempts were thwarted due to subtle limitations in the languages and runtime. However, there was another way and this post will go into the details.</p><p>One might be misled by the brevity of what I’m about to discuss but getting to this point entailed a lot of frustration and dead ends. While grit is the most important aspect of an engineer’s toolkit so is knowing when to quit. Quite honestly, I was about to give up on this problem and spend my time on a more fruitful endeavor but I caught a lucky break by revisiting a prior step with some newfound knowledge from along the way.</p><h4>Where I started</h4><p>Let’s rewind all the way to the beginning. I initially began this journey by reading the <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-authenticate-users.html">ALB documentation</a> to see if there was something simple we had missed. While there was nothing obvious, the docs did contain a snippet of Python for performing the verification. This was not super interesting in and of itself because it simply called Python’s JWT library to do the signature verification but it was a starting point since the example did work.</p><p>The example looked like:</p><pre>import jwt, requests, base64, json</pre><pre># Step 1: Get the key id from JWT headers (the kid field)<br>encoded_jwt = headers.dict[&#39;x-amzn-oidc-data&#39;]<br>jwt_headers = encoded_jwt.split(&#39;.&#39;)[0]<br>decoded_jwt_headers = base64.b64decode(jwt_headers)<br>decoded_jwt_headers = decoded_jwt_headers.decode(&quot;utf-8&quot;)<br>decoded_json = json.loads(decoded_jwt_headers)<br>kid = decoded_json[&#39;kid&#39;]</pre><pre># Step 2: Get the public key from regional endpoint<br>url = &#39;https://public-keys.auth.elb.&#39; + region + &#39;.amazonaws.com/&#39; + kid<br>req = requests.get(url)<br>pub_key = req.text</pre><pre># Step 3: Get the payloadpayload = jwt.decode(encoded_jwt, pub_key, algorithms=[&#39;ES256&#39;])</pre><p>Stepping through this example with a Python debugger and going down the call tree step by step provided a clue as to what was missing from the validation happening in Envoy/Lua.</p><h4>The signature</h4><p>To sign the JWT token the ALB requires three pieces of information 1) the data being signed 2) the private key and 3) a hash function. Per the documentation the ALB uses what is known as ES256 or ECDSA key + SHA256 hash function. The output of this signing function is two 256-bit integers referred to as <em>R</em> and <em>S</em>. The two integers are concatenated together forming 64 bytes which represents the full signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*tRjTLR7V2yiNroHI" /><figcaption>Illustrates that R and S are two 256 bit integers</figcaption></figure><p>When doing the verification we feed the verification function the data, public key, hash function, and signature (<em>R</em> + <em>S</em>). The verification function will tell us if the data was in fact signed by the public key’s corresponding private key, thus establishing the trust relationship.</p><p>I noticed when stepping through with a Python debugger that before the 64-byte signature was fed into the verification function, it was being split back into R and S and the two were converted into integers before being encoded into a <a href="https://datatracker.ietf.org/doc/html/rfc6979#section-2.4">DER encoded</a> <a href="https://datatracker.ietf.org/doc/html/rfc6025">ASN.1</a> structure. ASN.1 is simply an encoding format dating back to 1984 which remains popular in cryptographic applications like OpenSSL. The discovery of the splitting, converting to integers, and encoding seemed “interesting”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1V8OTx2kk2dpUlsD" /><figcaption>Stepping through into jwt/utils.py and its use of encode_dss_signature</figcaption></figure><p>Knowing the signature may need to be encoded gave a hint as to why it wasn’t working in our Lua script. A quick read of the Envoy docs and following the source code showed the verification function in Envoy’s Lua was actually backed by a C++ helper function. The helper function calls the<a href="https://www.openssl.org/docs/man1.1.1/man3/EVP_DigestVerify.html"> EVP_DigestVerify</a> function in OpenSSL which performs the validation. While documentation for this function is rather scant, googling around for usages of it in other projects showed that the signature was being encoded beforehand.</p><h3>Finding a solution</h3><p>At this point the obvious problem of why the signature verification was failing was solved. The less obvious and trickier problem was how do we encode the signature before passing it to the verification function. This finally brings us to the crux of this fun little problem.</p><h4>Comparing outputs</h4><p><em>How does one encode ASN.1 in Lua?</em> The obvious answer is you turn to GitHub and find a library someone already wrote, something like this <a href="https://github.com/nmap/nmap/blob/master/nselib/asn1.lua">one from NMAP</a>. But what if that doesn’t work? It initially didn’t work because the library was written for a newer version of Lua than what Envoy supported. After some modifications to replace new language function calls with older ones I got the encoder running but it was producing the wrong output. I knew this because I had the output from the encoder running in Python and was able to compare the two.</p><pre>[slava]$ <a href="https://man7.org/linux/man-pages/man1/hexdump.1.html">hexdump</a> lua_output.bin<br>0000000 <strong>30</strong> 0c <strong>02 04 71 6d fb 33</strong> 02 04 <strong>ce 83 66 58<br></strong>000000e</pre><pre>[slava]$ hexdump python_output.bin<br>0000000 <strong>30</strong> 45 <strong>02 20 71 6d fb 33</strong> 00 91 74 3e a8 92 ce 3c<br>0000010 e0 7c 30 cf b8 5d 08 62 5d 82 c1 31 a5 95 93 11<br>0000020 d1 77 bc 81 <strong>02</strong> 21 00 <strong>ce 83 66 58</strong> a5 11 57 23 30<br>0000030 59 0f 80 3e f3 a9 ae 25 9a d5 ed 20 84 50 57 94<br>0000040 52 6c 92 6e 2b 99 2c<br>0000047</pre><p>At a first glance those two outputs don’t look similar at all but on a closer inspection they do have some similarities which I’ve marked in bold. Somehow only part of <em>R</em> and <em>S</em> are being encoded. A good guess would be that there’s truncation happening here.</p><p>As it turned out, unpacking an integer represented by a 256-bit array into an integer primitive in Lua simply wasn’t going to work in a language that primarily dealt with 32-bits. This is the point where I almost gave up because going off and writing an unpacking library that made use of bigint under the hood and somehow tying that into the ASN.1 encoder was more work than I wanted to do at that point.</p><h4>Noticing a pattern</h4><p>Then I saw a commonality. What if I could take a shortcut? While I was playing around with the <a href="https://cryptography.io/en/latest/hazmat/primitives/asymmetric/utils/#cryptography.hazmat.primitives.asymmetric.utils.encode_dss_signature">encode_dss_signature</a> function in Python I started to notice a pattern.</p><pre># Bit of python that encodes R and S into ASN.1 and then writes the<br># signature into a file.</pre><pre>from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature</pre><pre>r = 42<br>s = 63</pre><pre>sig = encode_dss_signature(r, s)</pre><pre>f = open(f&#39;/tmp/{r}_{s}.bin&#39;, &#39;wb&#39;)<br>f.write(sig)<br>f.close()</pre><p>Using the <a href="https://man7.org/linux/man-pages/man1/hexdump.1.html">hexdump</a> cli tool we can print the encoded binary files out in hex format.</p><pre># r = 42  hex value: 2a<br># s = 63  hex value: 3f</pre><pre>[slava]$ hexdump 42_63.bin<br>0000000 <strong>30 06 02</strong> <strong>01</strong> 2a <strong>02</strong> <strong>01</strong> 3f</pre><pre># r = 12   hex value: 0c<br># s = 127  hex value: 7f</pre><pre>[slava]$ hexdump 12_127.bin<br>0000000 <strong>30 06 02</strong> <strong>01</strong> 0c <strong>02</strong> <strong>01</strong> 7f</pre><pre># r = 4277071598   hex value: feeeeeee<br># s = 4294967295   hex value: ffffffff</pre><pre>[slava]$ hexdump bignums.bin<br>0000000 <strong>30 0e 02 05 </strong>00 fe ee ee ee <strong>02 05</strong> 00 ff ff ff ff</pre><p>The pattern was that the bytes of <em>R</em> and <em>S</em> were directly sandwiched between some bytes that typically were the same except when <em>R</em> and <em>S</em> grew in <em>bignums.bin</em>. A thought popped into my head, I don’t actually need to convert the two into integers if the ASN.1 encoder is simply turning the integer value back into a series of bytes.</p><h4>Making sense of the pattern</h4><p>I found the <a href="https://www.openssl.org/docs/man1.1.1/man1/openssl-asn1parse.html">openssl asn1parse</a> command as part of the openssl cli tool which provided structural information about the encoded signature file.</p><pre>[slava]$ openssl asn1parse -in 42_63.bin -inform der -i<br>   0:d=0  hl=2 l=   6 cons: SEQUENCE<br>   2:d=1  hl=2 l=   1 prim:  INTEGER           :2A<br>   5:d=1  hl=2 l=   1 prim:  INTEGER           :3F</pre><p>The key thing to note from the above command output is the file has a structure to it. Specifically there are references to <em>SEQUENCE</em> and <em>INTEGER</em>. This makes sense since we encoded two integers. The sequence must be referring to essentially a list of things of which we have two integers.</p><p>I typically look at the official <a href="https://en.wikipedia.org/wiki/Request_for_Comments">Request For Comments</a> docs detailing this sort of thing but in this case I had some trouble understanding the encoding scheme as detailed in <a href="https://datatracker.ietf.org/doc/html/rfc6025#section-2.1.2">rfc6025</a>. After a bit of Googling I found the following table that helped explain what I was seeing in the <em>hexdump</em> output in relation to the output from <em>asn1parse</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*I8_T99K9EZ8uBrNO" /><figcaption><a href="https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/#tag">https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/#tag</a></figcaption></figure><p>A <em>SEQUENCE</em> is defined by the hex value of 30 and <em>INTEGER</em> by hex value 02 . Piecing it together we can decipher the hexdump of<em> R = 42 (2a)</em> and<em> S = 63 (3f)</em> .</p><pre># r = 42  hex value: 2a<br># s = 63  hex value: 3f</pre><pre>[slava]$ hexdump 42_63.bin<br><strong>30</strong> <strong>06</strong> 02 01 2a 02 01 3f<br>^^ ^^<br>|<br>|+- Sequence (<strong>30</strong>) of length 6 (<strong>06</strong>) bytes</pre><pre>30 06 <strong>02</strong> <strong>01</strong> <strong>2a</strong> 02 01 3f<br>      ^^ ^^ ^^<br>      |+- Integer (<strong>02</strong>) of length 1 (<strong>01</strong>) byte with value <strong>2a</strong></pre><pre>30 06 02 01 2a <strong>02 01 3f<br>               </strong>^^ ^^ ^^<br>               |+- Integer (<strong>02</strong>) of length 1 (<strong>01</strong>) byte of value <strong>3f</strong></pre><h4>Finding a solution</h4><p>From here, we can compose an ASN.1 DER signature fairly easily since we have <em>R</em> and <em>S</em> along with their lengths. I’ve included an example solution on GitHub along with a working Envoy configuration to see this in action.</p><p><a href="https://github.com/stlava/envoy-asn1-example">GitHub - stlava/envoy-asn1-example</a></p><h3>A look back</h3><p>This was quite the adventure from where we began with the initial problem statement of wanting to use a load balancer to do user authentication and verifying requests in the service mesh. For me it involved reading mounds of documentation and technical blog posts like this one. As a result, I now know a whole lot more about Lua, ASN.1 and JsonWeb Tokens and I also dove into web assembly with TinyGo and TypeScript. Every day isn’t like this, but this little adventure is representative of the broad domain an engineer may work through in a role on this team.</p><h4>Conclusion</h4><p>In closing, I want to touch upon a few parting thoughts for new readers. Operations is an ever evolving field with team titles like SRE, DevOps, DevSecOps, Cloud Engineers, and others people keep inventing. An engineer on one of those teams may be working on completely different tasks than their counterpart at a different company.</p><p>A successful DevOps engineer may not be a subject matter expert like their peers on other teams but they nonetheless possess a powerful toolkit. Simply reflecting on this adventure I’d include the following:</p><ol><li>The ability to find and synthesize documentation and code in software they are not familiar with.</li><li>Being comfortable reading code in languages they do not practice.</li><li>The tenacity to walk into a problem space with a positive attitude.</li></ol><p>This list is by no means comprehensive and all of these skills are built up over time. However, for new readers just entering the field the most important thing is a willingness and commitment to learn and answer the question of: “<em>How does something work as you peel back the layers?</em>”</p><p>Don’t be afraid to ask and seek answers for questions like: <em>“</em><a href="https://github.com/alex/what-happens-when"><em>what happens when I type google.com in my address bar and hit enter?</em></a><em>”</em> or <em>“</em><a href="https://github.com/0xAX/linux-insides/blob/master/Booting/linux-bootstrap-1.md"><em>how does my computer boot up</em></a><em>?”</em></p><p><strong>Note:</strong> Some readers may look at this list and say these are traits of any successful engineer and while I agree with you, I would also argue DevOps and DevOps adjacent engineers need to walk into unfamiliar problems in foreign pieces of code day in and day out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1e02712d40c" width="1" height="1" alt=""><hr><p><a href="https://engblog.nextdoor.com/learn-devops-by-doing-d1e02712d40c">Learn DevOps by Doing</a> was originally published in <a href="https://engblog.nextdoor.com/">Nextdoor Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless ETL on AWS Lambda]]></title>
            <link>https://engblog.nextdoor.com/bender-ff65a6edee92?source=rss-d8db977cf129------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff65a6edee92</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Slava Markeyev]]></dc:creator>
            <pubDate>Mon, 02 Oct 2017 17:56:51 GMT</pubDate>
            <atom:updated>2017-10-02T23:36:52.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWyrzyhV3scgJPG7CSrt1A.png" /></figure><p>Serverless ETL is becoming the future for teams looking to stay focused on their core responsibilities rather than running a large infrastructure to power data pipelines. Nextdoor’s mission is to build community, and I joined the Systems Infrastructure team to help support product engineers in achieving that goal. The team’s responsibilities include managing the data ingestion pipeline which services 2.5 billion daily syslog and tracking events. We found that, as our data volumes grew, keeping the data ingestion pipeline stable became a full time endeavor that distracted us from our other responsibilities.</p><p>Upon joining Nextdoor, my first project was to replace the aging <a href="https://hortonworks.com/apache/flume/">Apache Flume</a>-based <a href="https://engblog.nextdoor.com/structured-logs-at-nextdoor-4004c7b4c2fd">pipeline</a>, which served the business well for years. As we investigated alternative solutions, we had two use cases in mind:</p><ol><li>Streaming logs into Elasticsearch with an SLA of 1 minute.</li><li>Writing partitioned batches of data into S3 with an SLA of 5 minutes. Specifically, the current hour’s data must be available no later than 5 minutes after the end of the hour. This is to support downstream ETL processes.</li></ol><p>Obviously, a streaming solution lends itself well to these requirements and there are a lot of options in this space. The popular traditional solutions include Flume, <a href="https://hortonworks.com/blog/storm-kafka-together-real-time-data-refinery/">Kafka+Storm</a>, <a href="https://www.confluent.io/blog/introducing-kafka-streams-stream-processing-made-simple/">Kafka Streams</a>, <a href="https://flink.apache.org/">Flink</a>, <a href="https://databricks.com/spark/about">Spark</a>, and many others. As well as up and coming solutions like <a href="https://aws.amazon.com/kinesis/streams/">Kinesis+Lambda</a> from Amazon, Cloud Dataflow from Google, Azure Functions from Microsoft, and IronWorker from Iron.io.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*2IgxhU_LeMF3BrVz13W5XQ.png" /></figure><h4><strong>The </strong>Divide</h4><p>All of these solutions have scale, performance, operational, and monetary tradeoffs, but there are two overarching schools of thoughts which stem from the advent of cloud based infrastructure as a service. You can either invest in operating your own infrastructure or offload that responsibility to an infrastructure as a service provider. Amazon Web Services (AWS) pioneered this field and this now allows many companies, like Nextdoor, to focus more on developing product rather than running infrastructure. Cloud providers like AWS have gone beyond simply offering to offload the hardware aspect of infrastructure by packaging and offering SaaS for commonly used services like webservers, databases, and now Big Data platforms.</p><p>For instance, Hadoop’s core services haven’t gone away but rather have been packaged into services like EMR, Qubole, and Altiscale to decouple running a cluster from running your queries and ETL jobs. Nextdoor’s Data/BI team uses Qubole in this manner.</p><h4>What is Serverless?</h4><p>Each of the Serverless options from Amazon, Microsoft, Google, and Iron.io have subtleties but the premise is you are able to create and upload code that is automatically run for you. You no longer need to worry about managing servers, services, and infrastructure. All of that is handled for you. This, of course, does not come without monetary cost — but in most cases, you will find cost savings in no longer running servers or not having a dedicated engineer operating your pipeline.</p><p>How do you fit ETL into this concept? Most of these providers also have various data store or data stream technologies which can be linked with your code. For instance, AWS Lambda is able to trigger your code each time a file is uploaded to S3 or events streamed to Kinesis or written to DynamoDB. All you have to do is supply is code to process that data.</p><p>Here’s an example of a Amazon Lambda function written in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34894b35a65f69494a4a6c448f1b07f9/href">https://medium.com/media/34894b35a65f69494a4a6c448f1b07f9/href</a></iframe><p>You can see how Serverless is a powerful shift in how ETL is performed. However, it is still a young approach and is missing some pieces such as standardization of code. Engineers are able to write lightweight functions to process data but this often leads to fragmentation of approaches within teams, organizations, and the greater open source community. Boilerplate logic for configuration, exception handling, deserialization, transformation, transport, retrying, and monitoring is constantly reimplemented, mis-implemented, and in some cases punted on. I aimed to solve this problem by developing Bender.</p><h4>Introducing Bender</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zPuEqN2jmB_8CVCn9FiMwg.png" /></figure><p>Bender provides an extendable Java framework for creating serverless ETL functions on AWS Lambda. Bender is split up into two components, Bender Core handles the complex plumbing and provides the interfaces necessary to build modules for all aspects of the ETL process, while Bender Modules implement the most common use cases.</p><p>When designing Bender, we wanted a function that we could easily reconfigure to handle different use cases while leveraging common boilerplate logic like error handling, statistical reporting, retrying, configuration, etc. Bender Core performs the batching and routing of data and provides interfaces for aspects of the ETL process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1Ths8IFFcHtYqEbvHF-gQ.png" /></figure><p>Out of the box, Bender includes modules to read, filter, and manipulate JSON data as well as semi-structured data parseable by regex from S3 files or Kinesis streams. Events can then be written to S3, Firehose, Elasticsearch, or even back to Kinesis.</p><p>It is easy to implement additional support for different data log formats found in AWS and on machines such as syslog, apache logs, VPC flow logs, etc, as well as different data sources such as DynamoDB and destinations like a SQL database.</p><p><a href="https://github.com/Nextdoor/bender">Nextdoor/bender</a></p><h4>Partitioning Example</h4><p>A common use case is to re-partition data files written by Firehose into a different structure. With Bender, this is easy to do with the partition operation. For instance, if your json has 3 fields (HOST, FACILITY, and EPOCH) that you wish to partition by, your configuration may look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bf51efc5f8d5339c9e4bea7af80aab8/href">https://medium.com/media/5bf51efc5f8d5339c9e4bea7af80aab8/href</a></iframe><p>Additional examples with full configuration and documentation are provided in Bender’s <a href="https://github.com/Nextdoor/bender/tree/master/sample_configs">sample configurations</a>. In a future part of this series, we will focus on the ins-and-outs of how we use Bender in our infrastructure and the implementation and design decisions we made when working with Lambda, Kinesis, and Elasticsearch.</p><h4>Final Thoughts</h4><p>Working with cloud based services doesn’t eliminate engineering effort — rather, it shifts it. My team, Systems Infrastructure, helps bridge the gaps between servers and services so that our engineers can focus on the main goal of Nextdoor: <em>building a private social network for neighborhoods</em>. This means that sometimes we run services and other times leverage cloud offerings while writing projects like <a href="https://github.com/nextdoor/bender">Bender</a> to make life easier.</p><p>Find this sort of stuff cool? The Nextdoor engineering team is always looking for motivated and talented engineers.</p><p><a href="https://nextdoor.com/jobs/">Careers at Nextdoor</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff65a6edee92" width="1" height="1" alt=""><hr><p><a href="https://engblog.nextdoor.com/bender-ff65a6edee92">Serverless ETL on AWS Lambda</a> was originally published in <a href="https://engblog.nextdoor.com/">Nextdoor Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating AWS ACM cert validation options]]></title>
            <link>https://engblog.nextdoor.com/automating-aws-acm-cert-validation-options-9d1cd1081f0f?source=rss-d8db977cf129------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d1cd1081f0f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Slava Markeyev]]></dc:creator>
            <pubDate>Tue, 11 Jul 2017 17:18:32 GMT</pubDate>
            <atom:updated>2017-07-11T17:18:32.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ed7CFcR2MISZZHIMW2bvFg.jpeg" /></figure><p>At Nextdoor, the Systems team uses <a href="https://aws.amazon.com/cloudformation/">AWS CloudFormation</a> stacks paired with <a href="https://github.com/Nextdoor/kingpin">Kingpin</a>, a tool for orchestrating multiple APIs, to manage our cloud resources via code. Resources can be S3 buckets, Kinesis Streams, IAM policies, or in this article’s case Security Certificates.</p><p>When a certificate is requested via AWS Certificate Manager (ACM), a validation must take place before the certificate is issued. ACM looks up the WHOIS contact information for the specified domain and sends emails to those contacts to validate ownership and approve the cert creation. As noted in the <a href="http://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate.html">AWS documentation</a>, the apex domain should be used as the validation domain. For example, <em>foo.bar.example.com</em> should use <em>example.com</em> as it’s validation domain.</p><p>This is what the an ACM certificate resource looks like in a CloudFormation stack. Note the DomainName and the ValidationDomain properties:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4ca6a43b7a49f826066820943520943/href">https://medium.com/media/a4ca6a43b7a49f826066820943520943/href</a></iframe><p>A templated version of the above would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10ca610d3b186fe813add18137883446/href">https://medium.com/media/10ca610d3b186fe813add18137883446/href</a></iframe><h4>Using CloudFormation for Multi-Domain Certificates</h4><p>The above snippet becomes fairly convoluted when you want to template this for a multi-domain certificate. A user would have to specify the DomainName, SubjectAlternativeNames (SANS), and the mapping for each SAN to put into the DomainValidationOptions. Since the apex domains are different for each SAN — separate validation domains need to be specified.</p><p>A non-templated stack resource would look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a04560d4e1892f9c7d21f360faee652b/href">https://medium.com/media/a04560d4e1892f9c7d21f360faee652b/href</a></iframe><p>CloudFormation does not currently generate the DomainValidationOptions from the SubjectAlternativeNames list. However, one can leverage a simple Lambda function within a stack to do just that.</p><h4>Generating a list of ValidationDomains via AWS Lambda</h4><p>CloudFormation can manage a custom resource through an API endpoint. Combining this with AWS Lambda we can generate validation options from a list of SANs domains.</p><p>The function accepts a list of SANS:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0556e95885080a75dff2482debde4e25/href">https://medium.com/media/0556e95885080a75dff2482debde4e25/href</a></iframe><p>and returns the validation options to the stack in the following format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/908bcd6eedcaa9e21510e2110c3e6dcd/href">https://medium.com/media/908bcd6eedcaa9e21510e2110c3e6dcd/href</a></iframe><p>The stack is then able to use the map by calling:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df39af1e8d161012f43a9db348687e82/href">https://medium.com/media/df39af1e8d161012f43a9db348687e82/href</a></iframe><h4>Solution</h4><p>Here is the complete CF stack that utilizes the function. Note for clarity I’ve separated the python code out of the stack, but it is meant to be pasted inline.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcccde7f8d8594e67f5e3d0ac5e63ebb/href">https://medium.com/media/dcccde7f8d8594e67f5e3d0ac5e63ebb/href</a></iframe><p>Here’s the python lambda code that does the lookup to find the apex domain for a provided subdomain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ead15bc5972975ee2276c53a930074eb/href">https://medium.com/media/ead15bc5972975ee2276c53a930074eb/href</a></iframe><h4>Final Thoughts</h4><p>Nextdoor’s engineering culture has always encouraged automating little things like cert validation options. This project started off as a personal hunch for an easy win, and now we are able to re-evaluate our use of web certificates across the company.</p><p>Find this sort of stuff cool? The Nextdoor engineering team is always looking for motivated and talented engineers.</p><p><a href="https://nextdoor.com/jobs/"><em>Make your impact on Nextdoor’s engineering culture</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d1cd1081f0f" width="1" height="1" alt=""><hr><p><a href="https://engblog.nextdoor.com/automating-aws-acm-cert-validation-options-9d1cd1081f0f">Automating AWS ACM cert validation options</a> was originally published in <a href="https://engblog.nextdoor.com/">Nextdoor Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>