<?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 Rohan Ramchand on Medium]]></title>
        <description><![CDATA[Stories by Rohan Ramchand on Medium]]></description>
        <link>https://medium.com/@rohan.ramchand?source=rss-add6e834557d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Eo_xozbIqrR6RGBU</url>
            <title>Stories by Rohan Ramchand on Medium</title>
            <link>https://medium.com/@rohan.ramchand?source=rss-add6e834557d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:12:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohan.ramchand/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[Cutting over large systems]]></title>
            <link>https://tech.affirm.com/cutting-over-large-systems-fd099a1530ad?source=rss-add6e834557d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd099a1530ad</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Rohan Ramchand]]></dc:creator>
            <pubDate>Fri, 19 Oct 2018 02:44:05 GMT</pubDate>
            <atom:updated>2018-10-19T17:06:29.841Z</atom:updated>
            <content:encoded><![CDATA[<p>Affirm’s promotional messaging engine — the software that powers the 70 million messages we show on our partners’ websites every day — was in desperate need of a refactor. The data models had become so irrelevant that we had to spend precious CPU cycles munging [1] them into something more usable. The rendering logic — the code that takes a template like “As low as {payment}/mo” and injects the actual data — had become so bloated with new features that even though I wrote much of the original code, I had a hard time navigating it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*aDjibtF8yhbCdKoM.png" /><figcaption>Courtesy of <a href="https://xkcd.com/2054/">XKCD</a>.</figcaption></figure><p>For the most part, things worked and were relatively performant. But modules began getting so haphazardly stacked one on top of another that a small breeze could’ve knocked the whole system over. For a long time, this problem was ignorable. Once discovered, it was classified as tech debt. It stayed there for a while, a known problem that we didn’t <em>need</em>, strictly speaking, to solve, as we waited for an opportunity to pay down the debt while solving a product need.</p><p>Eventually, that opportunity arrived in the form of a new feature that necessitated a new column in the promo data structure. We started small by rewriting the object model, running a schema (and data) migration, and refactoring the rendering code to use the new data structure. We were able to leave the read/write code paths mostly untouched, except to use the new data. We’d need to add some tests here and there to maintain our test coverage, but our existing tests would cover everything else.</p><p>I was assigned the responsibility of writing the tech spec. I started with that vision of small, incremental changes, but as I wrote more of the spec it became clear that we could knock out all of the tech debt in the promo stack — and there was a lot of it — with this refactor. A few changes were necessary; for example, the UI for the write path had to be rewritten so significantly that it wasn’t worth trying to use the existing code. Others weren’t strictly needed (we likely could have strong-armed some of our existing code to serve our needs) but would make our lives a lot easier in the long run.</p><p>So we rewrote the whole service. Top to bottom, back to front, database to API endpoint. Once the code was completed, we couldn’t just merge it to production and call it a day. Promos are loaded three to four thousand times as often as the next most-used product (checkout) and are the first interaction most of our users have with us. It is the single most visible part of Affirm and, as a result, errors can be catastrophic [2].</p><p>In this post, I’ll cover some of the ways we handle this kind of backend cutover.</p><p><strong>What are promos?</strong></p><p>Promos are the core of Affirm’s branding strategy. Here’s <a href="https://www.boostedboards.com/boards/boosted-mini">an example</a> from one of our partners. The text that loads on the page, “Starting at $66/month with Affirm”, provides a basic summary of our financing options for the product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*suZJ2DF45e3biMsw" /><figcaption>The as-low-as component of a promo, which is rendered directly on a merchant’s website.</figcaption></figure><p>Clicking on “Learn more” opens a modal with more details about the financing offer (and some legal disclosures):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m8SAOj4flRJ7W358" /><figcaption>The modal component of a promo.</figcaption></figure><p>Promos have to be customizable, unobtrusive, and fast. More importantly, any financial statements we make have to be accurate to the penny. As a result, unlike many other parts of a promo, which are (relatively) static, payment estimates have to be calculated dynamically for every request.</p><p><strong>What’s at stake?</strong></p><p>It’s worth reviewing what could happen if the cutover goes wrong. Our frontend system handles general backend errors by showing default language. In general, really catastrophic errors are handled somewhat gracefully. Exceptions are logged to a centralized system and we have alerts set up if the number of 500s returned by the backend get too high.</p><p>The real problem isn’t the loud failures, but the quiet ones. Endpoints can, and do, return 200s even if something unexpected happens. If the cutover works but the promo language shows up wrong — for example, if the payment estimate is incorrect [3] — it becomes difficult to detect until one of our users notifies us of the discrepancy. Any reasonable hierarchy of errors should have user-reported, un-logged issues at the very top.</p><p><strong>Use integration tests</strong></p><p>In the <a href="https://martinfowler.com/bliki/TestPyramid.html">pyramid of testing</a>, the bottom layer is made up of unit tests. These are small tests that ensure every little component works as expected. Generally speaking, unit tests work by mocking out everything below the unit on the stack. Databases can be mocked out or stubbed [5], for example, as can services and any other external dependency. In addition to making sure everything works as expected, they also ensure that no one else can (unknowingly) break the unit.</p><p>The next level up is service-level testing, or integration testing. These are API-level tests that make sure that the output of a given API endpoint is correct. Integration tests don’t mock anything — the databases, services, and even the HTTP routes are real. While in theory you could test every single possible permutation of inputs, outputs, side effects, and states of the world, you don’t need to — that’s what unit tests are for. We use integration tests mostly to test happy paths, and if we do test any sad paths, they’re usually known-exception flows [5].</p><p>Integration tests are great for cutovers, where the goal is to make sure that every conceivable combination of input-output pairs stays the same between the old and new code. We use <a href="https://github.com/behave/behave">behave</a>, which tests “scenarios” written in natural language. One example test is as follows:</p><pre>Scenario: rendering a promo is successful<br> Given a promo<br> When the promo is rendered<br> Then I should get a 200 status code<br> And the rendered promo should match defaults</pre><p>In this test, the first step generates a promo to render and the second step actually calls the rendering function. The third and fourth steps ensure that the output is what we expect it to be.</p><p>Because we want to keep the API consistent, the inputs and outputs to the promo engine before and after the refactor need to be identical. As a result, the behave test can (and should) look more or less the same. We’re fetching and rendering a new object — so that has to be accounted for — but the output should be exactly the same as it was before.</p><p>As a result, by simply pointing all of our behave tests to the post-cutover code path, we are given complete testing for free. We have to add new scenarios to test net new functionality, of course, but the majority of the code — and all of the happy paths — are tested for free with our existing suite.</p><p>In fact, the behave framework provides a useful tool for this exact situation, called “scenario outlines”. These outlines allow you to combine a bunch of tests with similar steps into a single outline and template out the differences. In our case, all we had to do was this:</p><pre>Scenario Outline: rendering a <strong>&lt;renderable object&gt;</strong> is successful<br> Given a <strong>&lt;renderable object&gt;</strong><br> When the <strong>&lt;renderable object&gt;</strong> is rendered <br> Then I should get a 200 status code<br> And the rendered promo should match defaults</pre><pre> Examples:<br> | <strong>renderable object</strong> |<br> | promo |<br> | template |</pre><p>Because the outputs are identical, the last step can stay the same.</p><p><strong>When in doubt, run both</strong></p><p>Of course, even though our existing testing is pretty extensive [6], they’re necessarily incomplete. Promos are customizable by our merchants, so we can’t ever be certain that we’ve tested every possible scenario that might come up in the real world. In theory, integration tests should be complete enough, plus or minus some manual testing, to give you the confidence to make your changes in production.</p><p>Promos are so critical, though, that we can’t rely on that assurance alone. The old version of the code was, for better or for worse, the “right” version. Any discrepancies between it and the new version should be resolved by preferring the old version (except in the case of net new features). We need a sense of why and how often differences happened, and fix them accordingly.</p><p>So, we have to test in prod [7].</p><p>Not really, of course. A very small fraction of the time (less than 1% at the beginning), our requests hit both endpoints. The outputs are compared and if there’s a difference, we log it. (We also log the times when the outputs are identical for completeness.) This comes at a cost to performance, but the costs are outweighed significantly by the benefits. We can never be totally confident that we’re always going to be correct, but getting it right for 1% of our traffic is a pretty good starting indicator that we’ll get it right for the other 99%.</p><p>It takes a little longer than diving into the deep end without canary-testing first, but the tradeoff is worth it. Once we’re confident that the two endpoints are identical, we can cut over to the new endpoint fully. (After that, you can find me laughing maniacally as I delete now-legacy code, trying to ignore the thought that the new code is going to be legacy sometime next week.)</p><p><strong>Plan your data migrations carefully</strong></p><p>Migrating data is hard. Things might get lost or modified in the shuffle in a way that makes them nearly impossible to recover. In our case, we didn’t need to modify any data (we just transferred everything to a new database) but we had a constant stream of writes to the old database we needed to preserve. We had to make sure that not only was every existing entry in the old database transferred, but that every update was migrated as well.</p><p>There are at least three ways of doing this that we considered. In any case, you need a data migration to copy everything over from one database to the other. This preserves every element in the table, at least as it existed at the start of the migration [8]. The tricky part is preserving the updates.</p><p>One option would be to modify the existing write paths to write to both tables. This would be deployed after the data migration to ensure that any row in the old table that was modified would have a corresponding row in the new table. The sequencing would look like this:</p><ol><li>Run the DM. Old DB now equals new DB.</li><li>Deploy the write-path modification. Any changes to the old DB are now also made to the new DB.</li></ol><p>What happens if a change is made between steps 1 and 2, though? The change wouldn’t make it to the new database, and would be lost once we moved read paths. (We could have instituted a maintenance window between when the migration finished and when the write-path modification finished deploying, but maintenance windows are generally solutions of last resort.)</p><p>Another option would be to run the data migration twice, and have it only copy over data between databases if the last-updated timestamp of the old data was newer than the last-updated timestamp of the new data. The sequencing would look like this:</p><ol><li>Run the DM. Old DB now equals new DB.</li><li>A change happens to row A. Its timestamp in the old DB is now newer than the timestamp in the new DB.</li><li>Move the read/write paths to the new DB. Nothing can be written to, or read from, the old DB from this point on.</li><li>Another change happens to row A. Its timestamp in the old DB is now older than the timestamp in the new DB.</li><li>Run the DM again. Everything is mostly untouched, except for the row that was changed.</li></ol><p>This sequence obviates the need to write code that modifies the write path to write to two places, but also means that we can’t gradually transition from the old read path to the new one. That’s a huge downside.</p><p>The first approach is conceptually sound, but we can avoid the maintenance window by running the sequence backwards, as follows:</p><ol><li>Deploy the write-path modification, but only modify a promo if it already exists in the database.</li><li>Run the data migration. At this point, the two DBs are in sync.</li></ol><p>This approach doesn’t require a maintenance window [9]. It’s not as clean (arguably) as the second approach since we still have to write the write-path modification code, but it solves all of our problems with no need for a maintenance window.</p><p><strong>Conclusions</strong></p><p>Cutting over a production system that operates at an enormous scale is, unsurprisingly, an involved problem, and requires a lot of careful planning to get right. There are plenty of other gotchas — for example, making sure that your performance remains at least constant — that I didn’t cover above. Any cutover of this magnitude, no matter how carefully planned, is going to surface some edge cases that you might not have considered during code creation or testing. These strategies are by no means a panacea, but they have helped us cut back on the number of failures of any order significantly and are a good runbook for thinking about migrating code at scale.</p><p>Promos are the entry point for the vast majority of our customers into Affirm. As a result, the more information and the more functionality we can build into them, the better. As we grow the promos engine out, the backend complexity is certainly going to increase and every change will still pose an interesting and unique problem.</p><p>Promos are a powerful feature, and there’s a lot we have planned for them. If working on high-scale products at a hyper-growth startup is your kind of thing, come check us out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*aB299G-gxXwJHHa5.png" /><figcaption>Also courtesy of <a href="https://xkcd.com/844/">XKCD</a>.</figcaption></figure><p><em>PS</em> I graduated from UT Austin (hook ‘em!) in December 2017, and I started at Affirm in March. One month into my first full-time job ever, I was given the opportunity to rewrite our promo rendering engine, the system that maps variables like term length and monthly payment estimate to their actual values. At first I thought I was lucky for being able to hit the ground running so quickly after I started, but my experience here has shown me that Affirm gives everyone that same chance. Making an impact quickly turned out to be my kind of thing. If you think it could be yours as well, <a href="http://affirm.com/careers">let us know</a>.</p><p>[1] A word that I am told means “manipulating data”, and have been reassured is in fact an English word. As far as I know, my adoption of the word could be part of an elaborate prank by my colleagues.</p><p>[2] I can say that with confidence, given that I’ve caused many of the ones we’ve had.</p><p>[3] In fact, in our case, getting the payment estimate wrong is a form of <a href="https://www.investopedia.com/terms/u/udaap.asp">UDAAP</a> (an unfair, deceptive, or abusive act or practice), and opens us up to some pretty stiff legal penalties.</p><p>[4] SQLite has a great in-memory database that we’ve occasionally used for stubbing a database without pretending it doesn’t exist at all.</p><p>[5] An example of a known exception is when you get denied for a loan during our approval process. It’s hugely important that that flow be tested. On the other hand, it’s not as important that the flow where a datacenter goes down be rigorously maintained. Unit tests can handle that case.</p><p>[6] Modulo the catastrophic errors I mentioned above.</p><p>[7] “Everyone has a testing environment. Some people are lucky enough to have a separate production environment.” — me, right before I deploy broken code</p><p>[8] In theory, the migration runs sequentially on each row, so it’s possible that an update could still be preserved if it was made to a row not yet processed by the migration, but that’s in the realm of behavior I’m happy to leave undefined.</p><p>[9] Except while the DM is running, modulo the above footnote. We use <a href="https://github.com/spotify/luigi">luigi</a> to run our tasks, though, and so we can schedule our DMs at arbitrary hours (e.g., 2 AM–5 AM) to minimize the chance of an edit happening in the meantime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd099a1530ad" width="1" height="1" alt=""><hr><p><a href="https://tech.affirm.com/cutting-over-large-systems-fd099a1530ad">Cutting over large systems</a> was originally published in <a href="https://tech.affirm.com/">Affirm Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>