<?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 danny on Medium]]></title>
        <description><![CDATA[Stories by danny on Medium]]></description>
        <link>https://medium.com/@1092380912893?source=rss-b0dfce1d5bc3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aiBTuzdHiCZDNOn03DYu-Q.jpeg</url>
            <title>Stories by danny on Medium</title>
            <link>https://medium.com/@1092380912893?source=rss-b0dfce1d5bc3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:04:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@1092380912893/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[Fast, Reliable Serverless: From 50 minutes to 50 seconds a year of downtime on AWS]]></title>
            <link>https://medium.com/runa-engineering/fast-reliable-serverless-from-50-minutes-to-50-seconds-a-year-of-downtime-on-aws-88bd5b1b330b?source=rss-b0dfce1d5bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/88bd5b1b330b</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[response-time]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <dc:creator><![CDATA[danny]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 15:26:11 GMT</pubDate>
            <atom:updated>2024-10-10T21:11:30.841Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>At Runa, we’re always striving to build the most performant products possible. I work on the Ledger team, a sub-team of engineering. Our focus is to enable each engineering team to transfer money with speed, accuracy, and ease.</p><p>Our approach to solving this problem is to create an interface over our core ledger. This prevents our other teams from getting bogged down with the complexities of this source of truth. This has allowed them to move with speed and efficiency while keeping the core ledger accurate and intact.</p><p>We achieve this through a set of APIs. They make up the Payment Intents service. In simple terms, they are like your bank’s concept of authorizing and settling a transaction.</p><p>This service is integral to our platform’s functionality, as fundamentally, the purpose of Runa is to move value with ease. Two key requirements, besides correctness, were high reliability (&gt; 99.999%) and a fast response time.</p><p>We are plagued by what we call “phantom” requests. These are requests that AWS API Gateway receives, but never reach the resource, or return. AWS API Gateway has an SLA of just 99.95%, meaning that for a large volume endpoint, you are almost guaranteed to have requests getting lost in the network.</p><p>Below is a high level diagram of our architectural components. We often see the request from the API Gateway never reaching the Step Function, resulting in a timed-out request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zd-WyvmezAubdY0cSgZbHQ.png" /><figcaption>High Level Architectural Diagram</figcaption></figure><p>For an example of how the various SLA’s of AWS components can be compounded, see this post: <a href="https://www.linkedin.com/posts/theburningmonk_heres-a-reminder-that-the-benchmark-for-activity-7117198103497056256-s01D/">Yan Cui — Compounding SLA’s</a></p><p>We used the below methodologies to take our API’s from 99.99% to 99.997% (99.999% after discounting the phantom errors out of our control) across 4 million requests.</p><h3>Observability</h3><p>Everything here starts with observability. Observability encompasses all of our performance metrics, logging and incident management.</p><p>We must use a data-driven, scientific approach to improve performance. Often, things thought to improve performance do not, and vice versa. Without these starting benchmarks you have no indication of whether your change has had a positive or negative effect.</p><p>At a high level, the two metrics we care about for these benchmarks are <a href="https://www.notion.so/5ff32ba1ae9a4e41b8e4aa1605ae5f11?pvs=21">p95 response time</a>, and your 4xx/5xx error code rate. The server error/timeout reasoning is obvious. However, 4xx errors have nuances. Is your authoriser failing? Is a resource that should exist missing? Are you hitting rate limits? These should be tackled on a case-by-case basis.</p><p>Now, what tools do we use to get our benchmarks?</p><h4>Performance Testing</h4><p>To get where you need to be, you need to know what your starting point is. To do this, you’ll need to implement a performance test; it will give you a baseline for the responsiveness and stability under certain workloads. It is the basis for evaluating any changes we have made, to see if it has actually improved things! Without this you could worsen response time, or increased errors, which only occur under certain workloads.</p><p>At Runa, we have used <a href="https://www.artillery.io/">Artillery</a> extensively to perform our load testing. It’s a very simple tool to set up and use. It enables you to achieve distributed load testing and provides you with a breakdown of the stats: response time, error codes etc.</p><p>It provides you with excellent visualisations of these metrics, and allows you to compare previous runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjzEPp7rvC8fl0_JANzkyg.png" /><figcaption>Artillery Report</figcaption></figure><p>We used Artillery to measure all of the incremental changes to improve response time and reliability of our Payment Intents system. It highlighted multiple race condition issues and bottlenecks that we were not aware of until extensively testing.</p><h4>Visualisation</h4><p>Artillery gives us multiple snapshots of performance, but it does not show us a long term experience of our API users.</p><p>For this, at Runa, we have 2 options, Datadog, or AWS CloudWatch. We use Datadog for our longer term dashboards, but whilst troubleshooting ad-hoc issues or incidents, we lean on CloudWatch.</p><h4>Summary</h4><p>The two tools above should give you an idea of your system’s performance. Every system has its failure and slow points, and diagnosing them accurately can be a challenge. We’ll address this challenge in the next section.</p><h3>Diagnosis Tooling</h3><h4>Tracing</h4><p>Tracing gives us detailed execution diagnostics. It shows each component of an operation, from the gateway to the database. It can help you identify points of failure, slow components, and give you a better idea about your components’ topology.</p><p>Simply enable AWS X-Ray tracing on all your components; e.g Api Gateway resource, step function, lambda, etc.</p><p>With a few lines of configuration you can get a detailed map of the service, like below, with detailed execution durations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gq7cpRaATf_cESm_WlB7TA.png" /><figcaption>AWS X-Ray Trace Map</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcNjE48E6W-6ukas_dS5Rg.png" /><figcaption>AWS X-Ray Trace Waterfall</figcaption></figure><p>You can then use trace map analytics to aggregate and analyze these durations, giving you a detailed view of each component’s performance. This is essential to ensure you get the full picture of the response time of the component, and not just one offs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUrvm0WhTZoiVGf9lk-wcQ.png" /><figcaption>AWS X-Ray aggregated statistics</figcaption></figure><h4>Logs Insights</h4><p>If you use Lambda’s in your service, Logs Insights can help extract metrics that effect performance:</p><pre>filter @type = “REPORT” <br>| stats <br> count(@type) as countInvocations , <br> count(@initDuration) as countColdStarts ,     (count(@initDuration)/count(@type))*100 as percentageColdStarts,<br> max(@initDuration) as maxColdStartTime,<br> avg(@duration) as averageDuration,<br> max(@duration) as maxDuration,<br> min(@duration) as minDuration,<br> avg(@maxMemoryUsed) as averageMemoryUsed,<br> max(@memorySize) as memoryAllocated,  (avg(@maxMemoryUsed)/max(@memorySize))*100 as percentageMemoryUsed <br>by bin(1h) as timeFrame</pre><p>You can generate insights like the maximum cold boot duration for your lambda over time, shown in the graph below. Combining this with the number of cold boots during that period provides a solid basis for understanding what affects your response time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yOW0P2qcfWqXcou0oFaZA.png" /><figcaption>AWS Logs Insights graph for lambda statistics</figcaption></figure><h4>Summary</h4><p>These tools help us figure out what’s slow or unreliable. With these baselines, we can take a scientific approach to tweak, test, and iterate on improvements.</p><h3>Lessons Learned</h3><h4>Avoid lambda layers where possible</h4><p>Sharing code with Lambda Layers has been advocated as a simple way to reduce the amount of code you’re deploying, and improve cold boot duration. This is a common fallacy that is explained in far more detail in this <a href="https://aaronstuyvenberg.com/posts/why-you-should-not-use-lambda-layers">article</a>. You should read this separately, but the headlines are as follows:</p><ul><li>Lambda Layers do not improve or reduce cold boot duration</li><li>The size of the code you load is the sole biggest factor in cold start time. It doesn’t matter if it’s in your lambda or a layer.</li><li>Lambda layers can be a significant pain in the development process, as it means you will have “automagically” appearing dependencies in your lambda deployment. Debugging these is a PITA.</li><li>Lambda layers do not support semantic versioning, just a LATEST and incremental versions. This means that if you make a major version change that affects multiple lambdas, all of them must be ready to handle this change at the same time.</li><li>Dependency collisions are more likely using Lambda Layers.</li></ul><p>It’s also worth noting that the Datadog extension, which enables APM traces, can increase cold boot duration, as discussed in this article: <a href="https://medium.com/@adtanasa/the-latency-overhead-of-application-performance-monitoring-with-aws-lambda-extensions-896582da9b51">https://medium.com/@adtanasa/the-latency-overhead-of-application-performance-monitoring-with-aws-lambda-extensions-896582da9b51</a></p><p>Datadog has recently released an updated version of this layer, reducing the cold start impact of APM from 800ms to 400ms. However, this is still a significant delay, which is why the ledger team has chosen to use AWS Xray tracing for our critical low-latency lambdas where necessary.</p><h4>Improve your cold start duration</h4><p><strong>Package size</strong></p><p>The sole largest contributor to cold start duration is the size of your zip file. There is little way round decreasing your cold start duration without addressing this. The graph below shows the effect of package size on cold start durations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*T1_d_3htuyISsqZ5c_cWZQ.png" /><figcaption>AWS Lambda cold start duration by deployment size: <a href="https://mikhail.io/serverless/coldstarts/aws/">https://mikhail.io/serverless/coldstarts/aws/</a></figcaption></figure><p>Steps you can take to address this:</p><ul><li>Check for all non-essential dependencies and remove where possible.</li><li>Split up your internal dependencies into smaller modules that can be selectively bundled.</li><li>Use only the sub-parts of dependencies that you need, e.g @aws-sdk → @aws-sdk/dynamodb/client.</li><li>Move any dependencies required for development/testing to dev-dependencies.</li><li>Major improvements can be seen by using an adapted script that trims all non-essential files from node_modules. You can find a version of this script here: <a href="https://github.com/tuananh/node-prune/blob/develop/prune.sh">https://github.com/tuananh/node-prune/blob/develop/prune.sh</a>. We used this script to reduce our node modules size from ~14mb to ~400kb.</li></ul><p>We recommend using <a href="https://pnpm.io/">https://pnpm.io/</a> which ensures your lambdas are packaged only with what they need, reducing your bundle size dramatically.</p><p>These steps cut our P95 time by around 60ms for our critical endpoints — nearly a 20% reduction. This improvement came entirely from faster cold boot durations, which means bursty workloads are much less affected by cold starts. You can test these bursts of request volume in artillery by configuring different phases with quick ramp-up times.</p><p><strong>Keep your lambda outside of VPCs where possible</strong></p><p>VPCs are necessary for accessing certain resources like Redis and Postgres clusters. In your service, it might be tempting to put all your lambdas inside the VPC for easier development, but this approach increases your cold start duration.</p><p>Of course this is not always achievable, but be conscious of this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*FMHkUADIIj8D-O2XnS5jZg.png" /><figcaption>Cold start durations inside &amp; outside of a VPC: <a href="https://mikhail.io/serverless/coldstarts/aws/">https://mikhail.io/serverless/coldstarts/aws/</a></figcaption></figure><p><strong>Use AWS Lambda Power Tuning</strong></p><p><a href="https://github.com/alexcasalboni/aws-lambda-power-tuning">https://github.com/alexcasalboni/aws-lambda-power-tuning</a></p><p>AWS Power Tuning is a tool that you can use to optimise the amount of memory that your Lambda should be configured to use.</p><p>Memory in AWS Lambda’s is your 1 stop shop lever for increasing CPU, RAM, and network priority. Up to a point, it can yield big performance gains. See the graph below for the results of one of our Lambdas. We saved 50ms (33%!) off of our initialisation duration for a single config variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0uLXcshK4bsBvVq5a-Vlw.png" /><figcaption>AWS Lambda Power Tuning results</figcaption></figure><p>The graph above shows a sweet spot at 4096 (circled). There, invocation time and cost converge.</p><p>In our case, it’s not worth going much higher. The effect on performance improvements is minimal — it’s suspected that higher memory takes longer for AWS to allocate to a point.</p><p>Also worth knowing, is that the cost graph isn’t strictly true. It does not account for the decreased execution duration, below is an example from AWS over 1000 executions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmmGJrTNdo03aPwYpqLcWg.png" /><figcaption>Table of cost by execution duration and memory: <a href="https://repost.aws/knowledge-center/lambda-memory-compute-cost">https://repost.aws/knowledge-center/lambda-memory-compute-cost</a></figcaption></figure><p><strong>Initialise clients outside of the Lambda handler</strong></p><p>A crucial step in improving your Lambda’s performance is to reuse clients like Redis or DynamoDB between requests. To do this, make sure to initialize them outside of the Lambda handler.</p><p>This is because AWS Lambda uses a concept called “execution context” to improve performance. When a Lambda function is invoked, AWS Lambda creates an execution context to run the function. This context is maintained for some time in anticipation of another function invocation.</p><p>For example, the simple change below saved us 80ms off our p95 response time for this endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdJhItebxgmATKSICvlcng.png" /><figcaption>Initialising the Redis client outside of the Lambda handler</figcaption></figure><p>This change will yield a small increase in your initialisation duration the first time a Lambda is booted, but the subsequent requests will benefit greatly.</p><h4><strong>Favour direct integrations over generic calls from code</strong></h4><p>Where possible, using a step function direct integration is preferred, rather than integrating via Lambda code &amp; boto/aws-sdk. This approach reduces latency and the duration of Lambda invocations, ultimately decreasing overall cost.</p><p>For simple endpoints, using a Lambda function is often sufficient. However, when you need to orchestrate multiple steps, components, and service calls, it’s highly recommended to wrap your operation in a Step Function. AWS Step Functions give you out of the box observability, flexibility in extending your service, and, most importantly, leading on to the next point: native error handling and <strong>retries.</strong></p><h4><strong>Retry, retry, retry</strong></h4><p>This was learnt the hard way by the Ledger team, when we first released an early version of our Payment Intents service, we were being paged more than 20 times per week. All points of failure that could fail, did. Even retrieving secrets from SecretsManager!</p><p>To fix this, the team had to put in a lot of effort, adding retries to everything and making all calls that create a resource idempotent. As mentioned earlier, for instance, API Gateway’s SLA is only 99.95%, but since our client teams need to meet their 4 9’s SLOs, we had to achieve at least 5 9&#39;s.</p><p>This means that any operation involving a network call — whether it’s an API Gateway invocation, retrieving secrets, or publishing events — must be assumed to potentially fail, so you need to catch and retry it. Additionally, your services should be designed to be idempotent, allowing reliant API consumers to safely retry as well.</p><p>Using this methodology, we went from more than 20 errors a week, down to 0 errors over a 10 day period.</p><p>Step Function retries are much more robust and easier to implement than building these features into custom Lambda functions. We highly recommend this approach for a more reliable and observable service.</p><p>Our biggest takeaway from earlier versions was the importance of this approach, and we’ve made heavy use of it in our latest implementation to handle flaky network requests. Anywhere there’s a network call, it can break, and it will.</p><p>When setting up retries, be thoughtful about your configuration. Consider what you’re retrying and what you’re hitting. For example, we retry Redis operations five times in five milliseconds, but when dealing with legacy systems, we use a more gradual approach with exponential backoff. Each case is unique.</p><h4><strong>Can you do it asynchronously?</strong></h4><p>We can’t avoid the fact that our operations are slow and take a long time due to various reasons, such as relying on legacy services, third-party processors, or other slow dependencies.</p><p>Since these operations are critical but not time-sensitive and are required to generate a response to the client, they should be completed asynchronously. This can be done by invoking a step function asynchronously or using one of the many message brokers offered by AWS. You can find a comparison of their latencies for put and delivery here: <a href="https://lucvandonkersgoed.com/2022/09/06/serverless-messaging-latency-compared/">https://lucvandonkersgoed.com/2022/09/06/serverless-messaging-latency-compared/</a></p><p>The key is to keep critical operations simple and do as little work as possible before sending a response to the client.</p><p>By taking slow operations out of the critical path, we’ve significantly reduced our P95 latencies.</p><h4><strong>Use the correct component to store your configuration</strong></h4><p>This article provides more in-depth information than I will cover here: <a href="https://aaronstuyvenberg.com/posts/ultimate-lambda-secrets-guide">https://aaronstuyvenberg.com/posts/ultimate-lambda-secrets-guide</a></p><p>In summary, for configurations that don’t require frequent updates and aren’t sensitive, store them in environment variables instead of Parameter Store — it’s much faster and encrypted at rest.</p><p>For critical secrets that need quick retrieval, use Secrets Manager instead of Parameter Store secure strings.</p><p>Also, remember to use the retry policy mentioned earlier when fetching secrets in a Step Function. If you’re using secrets in a Lambda, consider retrieving them during initialization, outside of the handler, like we did with clients.</p><h4><strong>A note on provisioned concurrency</strong></h4><p>Provisioned concurrency, in simple terms, means having a set number of Lambdas always running, which avoids the cost of cold starts.</p><p>When configuring your Lambda, it can be tempting to use provisioned concurrency as the default option. However, this can be very expensive. For instance, a 4096mb Lambda with a provisioned concurrency of 10 would cost over £300 a month. If you have multiple Lambdas, the costs add up quickly.</p><p>If your Lambdas are serving a high volume of requests, you don’t really need provisioned concurrency — Lambdas stay active after the current execution for an <em>unspecified</em> amount of time, however with a high throughput you will almost definitely end up re-using already warm instances.</p><p>The CloudWatch metric ProvisionedConcurrencySpilloverInvocations can be a good indicator of whether your provisioned concurrency is not being used and you could afford to scale it back.</p><h4><strong>Where possible use resource based IAM policies</strong></h4><p>Using resource-based IAM policies instead of identity/role-based ones can significantly reduce the response time between your API gateway and compute resource, such as Step Functions or Lambdas. This simple change can produce dramatic results. For more details, see this excellent article: <a href="https://medium.com/@lancers/low-hanging-fruit-to-reduce-api-gateway-to-lambda-latency-8109451e44d6">https://medium.com/@lancers/low-hanging-fruit-to-reduce-api-gateway-to-lambda-latency-8109451e44d6</a></p><h3>Summary</h3><ul><li>Start with your benchmarks, you don’t know if you’ve improved things if you don’t know where you started.</li><li>Tracing gives you highly detailed diagnostic capabilities.</li><li>Logs insights can give you deeper insight to your Lambda init, cold start durations, and memory usage.</li><li>Think about your overall Lambda size &amp; whether it’s in a due to the impact on response time.</li><li>Initialise clients so that they can be reused across requests.</li><li>Step functions orchestrate even small operations, thanks to their retry and direct integration capabilities.</li><li>If it can be async, it should be async.</li><li>Use resource based IAM policies.</li></ul><h3>Recommended resources</h3><ul><li>AWS Well Architected — build secure, high-performing, resilient, and efficient infrastructure: <a href="https://aws.amazon.com/architecture/well-architected/?wa-lens-whitepapers.sort-by=item.additionalFields.sortDate&amp;wa-lens-whitepapers.sort-order=desc&amp;wa-guidance-whitepapers.sort-by=item.additionalFields.sortDate&amp;wa-guidance-whitepapers.sort-order=desc">https://aws.amazon.com/architecture/well-architected/?wa-lens-whitepapers.sort-by=item.additionalFields.sortDate&amp;wa-lens-whitepapers.sort-order=desc&amp;wa-guidance-whitepapers.sort-by=item.additionalFields.sortDate&amp;wa-guidance-whitepapers.sort-order=desc</a></li><li>Use direct service integrations to optimize your architecture: <a href="https://aws.amazon.com/blogs/architecture/use-direct-service-integrations-to-optimize-your-architecture/">https://aws.amazon.com/blogs/architecture/use-direct-service-integrations-to-optimize-your-architecture/</a></li><li>What are lambda extensions and why do they matter? <a href="https://lumigo.io/blog/aws-lambda-extensions-what-are-they-and-why-do-they-matter/">https://lumigo.io/blog/aws-lambda-extensions-what-are-they-and-why-do-they-matter/</a></li><li>Cold start time analysis: <a href="https://medium.com/@r_smith/aws-lambda-memory-duration-and-cold-start-time-analysis-bfcd78d2e58a">https://medium.com/@r_smith/aws-lambda-memory-duration-and-cold-start-time-analysis-bfcd78d2e58a</a></li><li>Improving Lambda cold starts: <a href="https://www.youtube.com/watch?v=IHFJ-0_3cXY">https://www.youtube.com/watch?v=IHFJ-0_3cXY</a></li><li>Improve performance of services by avoiding unnecessary parameter retrieval: <a href="https://aaronstuyvenberg.com/posts/ultimate-lambda-secrets-guide">https://aaronstuyvenberg.com/posts/ultimate-lambda-secrets-guide</a></li><li>Low hanging fruit to reduce AWS API Gateway Latency: <a href="https://medium.com/@lancers/low-hanging-fruit-to-reduce-api-gateway-to-lambda-latency-8109451e44d6">https://medium.com/@lancers/low-hanging-fruit-to-reduce-api-gateway-to-lambda-latency-8109451e44d6</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88bd5b1b330b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runa-engineering/fast-reliable-serverless-from-50-minutes-to-50-seconds-a-year-of-downtime-on-aws-88bd5b1b330b">Fast, Reliable Serverless: From 50 minutes to 50 seconds a year of downtime on AWS</a> was originally published in <a href="https://medium.com/runa-engineering">Engineering at Runa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing a database]]></title>
            <link>https://medium.com/runa-engineering/choosing-a-database-f173ea0d3181?source=rss-b0dfce1d5bc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f173ea0d3181</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[danny]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 14:15:10 GMT</pubDate>
            <atom:updated>2023-09-04T14:38:15.561Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Choosing a database</strong>: There’s more to life than SQL</h3><p><em>If you’re an engineer looking to join a mission-driven company with an amazing engineering culture — </em><a href="https://wegift.io/careers"><em>check out our careers page</em></a><em>!</em></p><p>Whether you’re building your first or your fiftieth application, choosing a database is one of the toughest choices to get right. It will be one of the first decisions you make, and will likely also be one that ingrains itself within your application. With a plethora of excellent databases available, and an overwhelming amount of information readily available, this only makes the task more difficult.</p><p>Our latest projects, and a desire to develop at pace here at <a href="https://runa.io/">Runa</a>, have necessitated a shift to an event driven architecture, which opens up a lot of opportunities to leverage the latest technologies. For our most recent project, we’ve had to select a database for a system with multiple 3rd party integrations which would return varying metadata, capable of facilitating a high number of transactions.</p><p>In this post I’ll give a concise overview of the common database types, their uses, and a few of the considerations that should be made when selecting a database that are less commonly mentioned.</p><h3><strong>What are the main types of database?</strong></h3><h4><strong>Relational Databases</strong></h4><p><em>Examples: </em><a href="https://www.postgresql.org/"><em>PostgreSQL</em></a><em>, </em><a href="https://www.mysql.com/"><em>MySQL</em></a><em>, </em><a href="https://www.oracle.com/uk/database/"><em>Oracle DB</em></a></p><p>Relational databases are the <a href="https://insights.stackoverflow.com/survey/2020#technology-databases">most commonly used type of database</a>. Data is organised in tables which, unsurprisingly, can have relations defined with each other using foreign keys. SQL allows you to query these tables and join them together, allowing you to efficiently retrieve data in a format that suits your requirement. Tables are structured using columns and rows, where columns define the data attributes and the rows define a record within the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*jeu2VpNMvgF9HPNt" /><figcaption><em>Figure 1: Example of a table in a relational database.</em></figcaption></figure><p>Relational databases ensure <a href="https://en.wikipedia.org/wiki/ACID">ACID</a> transactions, which means data integrity is always preserved. ACID transactions, coupled with the need to define models prior to data insertion, means that relational databases are perfect for when the consistency and stability of the data is integral to the behaviour requirements. However, this stability comes at the cost of flexibility.</p><p>The main downfall of relational databases is the scalability of the performance when a high volume of transactions are required, or if the geolocation of the database is important. The typical first port of call used to scale relational databases is to scale vertically, adding more computing power. However, this of course has its limitations. Beyond this, the use of sharding, caching and read replicas would need to be introduced, but<strong> this results in extra work to tackle these issues, which are often only realised when it’s evident that the database has become the bottleneck.</strong></p><p>The perfect use cases for relational databases are when the required data consistency is high, and relationships are well defined. A reporting system for an eCommerce platform where there are tables including customers, orders, payments and products would be a perfect candidate for a relational database. The reason being is that the relationships are well defined, the utilisation of transactions would be required, and the use of relationships to perform bespoke queries would be needed for any analytics or reporting. Another unspoken benefit of relational databases is the amount of documentation available which makes the development process easier.</p><h4><strong>Graph Databases</strong></h4><p><em>Examples: </em><a href="https://aws.amazon.com/neptune/"><em>Amazon Neptune</em></a><em>, </em><a href="https://neo4j.com/"><em>Neo4j</em></a></p><p>Graph databases are defined using nodes — which define the data stored — and edges, which store the relationships between nodes. This storage of relationships means that joining these sets of data is extremely quick, in contrast, a relational database would compute these at query time, slowing down the entire process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*u3pGa_PIo_AyTG07" /><figcaption><em>Figure 2: an example of a simplified graph database.</em></figcaption></figure><p>Utilising a graph database’s unique capabilities requires a querying language optimised to do so, which has resulted in a multitude of different query languages such as <a href="https://opencypher.org/">Cypher</a>, <a href="https://www.w3.org/TR/rdf-sparql-query/">SparQL</a> and <a href="https://tinkerpop.apache.org/docs/3.3.3/reference/#gremlin-applications">Gremlin</a>. These querying languages employ pattern matching to extract data. For example, if I wanted to query who Rob knows directly, a query in could look like this;</p><pre>MATCH (a:Person {name:”Rob”})-[:KNOWS]-&gt;(b)</pre><pre>RETURN b</pre><p>Intuitively, graph databases are great for storing data on how things are connected to each other, for example friends on a social network, advertisement display or fraud prevention. Conversely they are less suitable for storing things such as transaction histories. The support for ACID transactions and the ability to scale varies between each database, so it’s worth researching this prior to selection.</p><h4><strong>Document Databases</strong></h4><p><em>Examples: </em><a href="https://www.mongodb.com/"><em>MongoDB</em></a><em>, </em><a href="https://docs.couchdb.org/"><em>CouchDB</em></a>, <a href="https://www.elastic.co/"><em>ElasticSearch</em></a></p><p>Document databases typically store data as structured nested documents (think JSON/BSON, XML), meaning that they intuitively correspond to the objects in your code. These <em>documents</em> are stored in <em>collections</em>, and are analogous to a row and table in a relational database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*brE2YDSP-N1dghSo" /><figcaption><em>Figure 3: an example of a document.</em></figcaption></figure><p>The documents allow you to store semi-structured information using flexible schemas, allowing you to update due to changing requirements easily. In this respect, this is one of the main differences to relational databases which would require an SQL statement to update the schema. This flexibility makes document databases great for storing anything that will potentially have varying content, but you need flexible querying; think product information or customer details.</p><p>Most document databases support a join functionality in one form or another, however the way that documents are designed to be used, means that you typically shouldn’t. For example a customer and customer contact details would typically be stored in 2 separate tables in a relational database, however in a document database you would utilise the hierarchical structure to store them within a single document.</p><p>Most document databases also support ACID transactions, and typically support horizontal scaling; this scaling allows you to support huge volumes of read queries. MongoDB also supports strong consistency (linearizability), which is always handy.</p><h4><strong>Key/Value Databases</strong></h4><p><em>Examples: </em><a href="https://redis.io/"><em>Redis</em></a><em>, </em><a href="https://www.oracle.com/database/technologies/related/berkeleydb.html"><em>Berkeley DB</em></a></p><p>Key/value stores are the most conceptually simple of the databases; it is a non-relational database where values are stored against keys. These values can be as simple as a single piece of data, up to more complex objects, similar to documents. This sounds extremely similar to a document database, however in a key/value database, the information stored against the key is less transparent. This means that for a document database, you can query against non-primary keys, allowing for higher flexibility, whereas with a key/value database, you are typically limited to querying against a single primary key.</p><p>While there is a lower level of flexibility within key/value databases, this results in a better performance on reads and writes, so there are benefits too! They’re best used when you know what you want to query. Then, finding the information of a known key is extremely quick, however, if you need to filter by a non-primary key, this becomes more difficult.</p><p>The use cases for key/value databases are quite similar to document databases; user profiles, session data or simply caching data. As with document databases, they typically also support horizontal scaling.</p><h4><strong>Wide Column Databases</strong></h4><p><em>Examples: </em><a href="https://cassandra.apache.org/"><em>Apache Cassandra</em></a><em>, </em><a href="https://cloud.google.com/bigtable"><em>Bigtable</em></a><em>, </em><a href="https://www.scylladb.com/"><em>ScyllaDB</em></a></p><p>When querying big data to generate analytics and reports, it’s rare that you wish to query every column of every row and quite inefficient to do so. Even when reducing the number of columns selected, this still can result in large volumes of unnecessary data being parsed! Wide column/column family databases, circumvent this issue by partitioning data in columns, and when it comes to querying, only the columns required are retrieved. The result of this is a sparse matrix of partitioned columns, containing a single data type (wide column), or column families which store a row, which in turn has nested columns and values within itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qG_3Jiu-TWGvHqFn" /><figcaption><em>Figure 4: Example of a wide column/column family database structure.</em></figcaption></figure><p>Wide column databases are fantastic for things like data logging, reporting and even message services — <a href="https://blog.discord.com/how-discord-stores-billions-of-messages-7fa6ec7ee4c7">Discord wrote a fantastic post</a> on their migration from MongoDB to Apache Cassandra. Their best use cases are when you have predictable query patterns, high write, and lower read frequency requirements. The sparse matrix design allows for high flexibility within the database; a row doesn’t have to use all columns, meaning different rows can be composed of different columns.</p><p>Wide column databases typically trade off this high write speed with lower linearizability (due to the horizontal scaling), meaning that when you query, you are not guaranteed to get the latest write information.</p><h3><strong>Factors to consider when choosing a database</strong></h3><h4><strong>The C’s in CAP and ACID are very different and aren’t particularly important.</strong></h4><p><strong>Two concepts I often see confused are the C’s in CAP and ACID; whilst both stand for <em>consistency</em> within these acronyms, they essentially mean two completely different things.</strong></p><p>Starting with the C in ACID, consistency here means that certain constraints or statements about your data must always be adhered to; be this type, certain combinations, limitations or uniqueness. This, however, is the limitation of a database’s capabilities with regards to consistency — anything more complex cannot be handled by a database. Most databases offer this level of consistency by default and it cannot substitute the invariants produced by business logic, and subsequently cannot prevent a transaction that neglects these from being completed. Thus, in my opinion, atomicity, isolation and durability are more important traits offered by databases, and things you should value more highly.</p><p>Conversely, the C in CAP (<a href="https://robertgreiner.com/cap-theorem-explained/">see flaws of CAP in this great article</a>), is better termed as <em>linearizability</em>, which can be simply broken down to mean: when a database is written to, any subsequent read will see the exact data that has just been written. As you can imagine in certain applications this is essential — for example checking a customer’s balance before an order, or the stock levels of a product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*PXX4i_4f9fNKevZq" /><figcaption><em>Figure 5: Example of how a lack of linearizability can impact application behaviour.</em></figcaption></figure><p>A lot of databases can offer linearizability despite having replicas, and while it’s not instantaneous, the latency between replication can be fast enough that it has no real-world implications for your application. Linearizability is also not an essential quality of a database and by sacrificing this you can gain in other areas, such as read and write speed. Examples of where high linearizability isn’t required could be a reporting system that aggregates the volume of orders made or how many users have liked a social media post — anything where the exact real time value isn’t required.</p><h4><strong>What kind of relationships are required?</strong></h4><p>When querying your data, what kind of relationships are required? In my opinion, this is one of the factors that differentiates the database types listed above the most; not SQL vs NOSQL. This question will largely depend on your application’s intended behaviour, and the architecture that it is constructed under.</p><p><strong>There is no one-size-fits-all database for this, and nor should anyone be under the illusion that using a single database type is the only way to go; separate services may require completely different databases. </strong>When first deciding what database you wish to use, model your data — define entities and relationships and it will likely become clear which database is most suitable for you. It’s also pertinent to mention that having relationships is not a necessity, if you can structure your data in such a way that avoids these relationships it can benefit your application’s performance; relationships always have a cost.</p><h4><strong>Requirements — are they well known?</strong></h4><p>This question is quite broad and can mean a plethora of prerequisites, from functional to non-functional. There are countless possible requirements beyond application behaviour; are you locked into a cloud provider? Do you need a fully managed service? How important is security? All of these things would not be considered primary requirements that were in the previous sections, however they all play a large role within the dynamics of selection of a database.</p><p>When you consider options outside of your hosting ecosystem, you open yourself up to spending far more time than initially budgeted for, managing these solutions — security updates, failovers and back ups. These of course all play second fiddle to the primary requirements of a database and the capabilities they give you, however it is imperative to consider these factors to avoid headaches further down the road.</p><h3><strong>Conclusions: How did we navigate this wonderland?</strong></h3><p>These considerations, along with the desire in agile development to move fast and iterate quickly, mean that spending the time early in the development process will pay dividends – migrations at a later stage are costly and ideally avoided. This decision will not only impact the performance of your application, but also the development process.</p><p>The factors listed above are not the only ones to consider, they are the factors I believe to be frequently overlooked. I thoroughly recommend spending a large amount of time reviewing and testing as many options as possible to understand the fundamental differences between each of the choices available.</p><p>After going through this process ourselves, it was between a key/value and document hybrid database and a document database. We narrowed it down to being between <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a> and <a href="https://aws.amazon.com/pm/documentdb/">DocumentDB</a> — a MongoDB fork by AWS.</p><p>Firstly, at <a href="https://runa.io/">Runa</a>, our current infrastructure is all on AWS; we want a managed service that performs security updates, backups, and scaling. Both of these support strongly consistent reads, which is what we’ll need as part of this feature.</p><p>Finally, the schema flexibility is perfect for our requirements; we’ll be storing varying metadata from third-party providers, and the desire to have a good developer experience is high up on our list; not having to write schema migrations definitely helps achieve this. We’re going to spend some time experimenting with the two, and I’ll be sure to update this post when we reach a conclusion.</p><p>Check back soon to see which of the two options we went for!</p><h3>Come work at Runa!</h3><p><em>We’re building an engineering team where people can do their best work. We want to hire talented engineers who see Runa as an opportunity to grow and to make a huge impact! We have structures in place from hiring and levelling to how we make technical decisions that really allow people to thrive. If you’re interested to find out more about life at Runa and how you can join us on our mission to revolutionise the $20 Trillion B2C pay-out market, then take a look at our </em><a href="https://wegift.io/careers"><em>careers page</em></a><em> or get in touch with </em><a href="https://www.linkedin.com/in/oliver-lochhead-803bb151/"><em>Oliver Lochhead</em></a><em> (oliver.lochhead@runa.io) in the Talent Team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f173ea0d3181" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runa-engineering/choosing-a-database-f173ea0d3181">Choosing a database</a> was originally published in <a href="https://medium.com/runa-engineering">Engineering at Runa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>