<?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 Jean Baptiste Muscat on Medium]]></title>
        <description><![CDATA[Stories by Jean Baptiste Muscat on Medium]]></description>
        <link>https://medium.com/@ouvreboite?source=rss-475d24faa679------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*bBCLwudej-ISTPZ_H-GxHw.png</url>
            <title>Stories by Jean Baptiste Muscat on Medium</title>
            <link>https://medium.com/@ouvreboite?source=rss-475d24faa679------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:17:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ouvreboite/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[Can you trust your OpenAPI spec?]]></title>
            <link>https://medium.com/criteo-engineering/can-you-trust-your-openapi-spec-a62677d43fb3?source=rss-475d24faa679------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62677d43fb3</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[stoplight]]></category>
            <dc:creator><![CDATA[Jean Baptiste Muscat]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 08:03:25 GMT</pubDate>
            <atom:updated>2025-01-27T15:03:55.377Z</atom:updated>
            <content:encoded><![CDATA[<h3>Detecting discrepancies between your OpenAPI specification and your API’s behavior</h3><p>Tools and tips to be sure your API behaves how you document it.</p><p><a href="https://www.openapis.org/">OpenAPI</a> (aka Swagger) is great. It started in 2011 as a simple format to auto-generate SDKs and human-readable documentation. It has since spawned a whole tooling <a href="https://openapi.tools/">ecosystem</a>, from advanced rulesets to ensure the consistency of your API with <a href="https://github.com/stoplightio/spectral">Spectral</a> to <a href="https://techblog.criteo.com/introducing-openapi-comparator-an-open-source-tool-to-detect-breaking-changes-in-your-api-7f705bb972b0">breaking change</a> detection.</p><p>Nowadays, many companies have pipelines dedicated to generating their public SDKs or documentation from their OpenAPI specification. But what happens if your specification is incorrect? And how can you find out?</p><h3>OpenAPI for everything</h3><p>Criteo’s public API has been constantly growing, and we use OpenAPI extensively: from linting, aggregating, and detecting breaking changes before release to generating our public SDKs and our public documentation. We spent a lot of time building and testing our pipeline to automatically and reliably ship up-to-date artifacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oOGZ5pYJNQD4ti-T" /><figcaption>Our OpenAPI pipeline (simplified)</figcaption></figure><p>And all that relies on the simple assumption: <strong>an OpenAPI specification accurately represents your API</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*2iw__n9xHbsmdrkgclfsOw.gif" /></figure><h4>So, what happens if that’s not the case?</h4><ul><li>your public documentation becomes inaccurate</li><li>your SDKs no longer work (<em>“Hey, why am I receiving a list of strings instead of a number?”</em>)</li><li>your breaking change detection is worthless</li><li>…</li></ul><p>In other words: <strong>garbage-in garbage-out</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IMA2JpskxroxkEwH" /><figcaption>Our OpenAPI pipeline if the initial OpenAPI specification is inaccurate</figcaption></figure><h3>An inaccurate OpenAPI spec?</h3><p>Let’s look at several ways your specification could diverge from your actual API’s behavior.</p><h4>Hand-written specification</h4><p>For small projects, manually writing the specification is a common strategy. As with anything manually written, it’s easy to make mistakes. Especially as OpenAPI is verbose. And quite complex when you start digging into complex schema.</p><blockquote><em>🤔</em>Should I use anyOf or oneOf here?</blockquote><h4>Abstraction over abstraction</h4><p>A good way to reduce the number of lines to write (and hopefully the number of mistakes), is to use more compact description languages, for example: <a href="https://typespec.io/">Typespec</a>. But to fully leverage the OpenAPI ecosystem, you still want an OpenAPI spec. Luckily, Typespec can generate a (big) OpenAPI specification from your (smaller) Typespec file. But, now you have to understand both Typespec and OpenAPI.</p><blockquote><em>🤔</em>Am I writing the correct Typespec code to generate the correct OpenAPI spec to represent the behavior of my API?</blockquote><h4>Server code-generation</h4><p>But, if an OpenAPI spec describes the shape of my API, can’t I generate the code of my controllers and DTOs from it? Sure, for example by using one of the 60+ server generators from <a href="https://openapi-generator.tech/docs/generators/#server-generators">OpenAPIGenerator</a>. But code generation is a complex beast, and not every OpenAPI feature is supported.</p><p>As an example, the Spring server generation does not support most of the “complex” schema patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*gRmql7mVaidzXHl8nnGipA.png" /><figcaption>Supported schema features for <a href="https://openapi-generator.tech/docs/generators/spring">spring</a> server-code generation</figcaption></figure><blockquote><em>🤔</em>If my OpenAPI spec contains non-supported features, will the server-code generation silently fail?</blockquote><h4>Code-first specification</h4><p>You can also choose the opposite solution: generate your OpenAPI spec from your server code. That’s common and most languages have their own “code-first” library. This works well until you start using idiomatic patterns from your language that do not map well to OpenAPI. Generic, tuples, … or even simply nullable properties (not supported in OpenAPI 2.0)</p><blockquote><em>🤔</em>If my API use patterns and data structure supported by OpenAPI, what happens? Will I even know?</blockquote><h4>Code is still manually written</h4><p>Producing a complete OpenAPI specification often requires more than can be directly inferred from your code. A common solution from code-first libraries is using attributes/annotations/… to finely describe an endpoint or model.</p><p>But those are mostly descriptive, and often not type-checked. For example, this is the standard way of documenting the status code and model returned by an endpoint in C#’s ASP.NET Core:</p><pre>[HttpGet(&quot;/products/{id}&quot;)]<br>//&quot;I&#39;m returning a 200 with a Product reponse or a 404, trust me&quot;<br>[ProducesResponseType&lt;Product&gt;(StatusCodes.Status200OK)]<br>[ProducesResponseType(StatusCodes.Status404NotFound)]<br>public IActionResult GetById_IActionResult(int id)<br>{<br>   //🐛 nothing you can write here will be checked <br>   //🐛 against what you put in [ProducesResponseType]<br>}</pre><blockquote><em>🤔</em>Does my endpoint actually return a 200 and/or a 404?</blockquote><p>Luckily, newer versions of ASP.NET Core support an alternative, better typed, syntax:</p><pre>[HttpGet(&quot;/products/{id}&quot;)]<br>public Results&lt;Ok&lt;Product&gt;, NotFound&gt; GetById(int id)<br>{<br>    var product = _productContext.Products.Find(id);<br>    return product == null ? TypedResults.NotFound() : TypedResults.Ok(product);<br>    //✅returning TypedResults.NoContent() will generate a build-time error<br>}</pre><p>But, as of <a href="https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/2595">October 2024</a>, <a href="https://github.com/domaindrivendev/Swashbuckle.AspNetCore">Swashbuckle</a> (the main C# OpenAPI code-first library) is not supporting this new syntax.</p><blockquote><em>🤔</em>Does my OpenAPI library understands all the features of my language?</blockquote><h4>JSON serialization</h4><p>Even if you use simple models and controllers, there is one more step: transforming your data from and to JSON. A lot of decisions are made here: casing, enum serialization, null values, and date formats, …</p><p>It’s the job of the code-first library to understand all that and create an accurate representation of the API. But it’s not an easy task. And, you can make this task very hard if you have some custom logic or use a serialization library that was not accounted for.</p><blockquote><em>🤔</em>For optional properties, does my API return ‘null’ if the prop is not filled or remove it from the output?</blockquote><h4>There shall be bugs 🐛</h4><p>Finally, where there is code, there are bugs. And now you are relying on a lot of code to create your spec 😉</p><p>All that considered, look at the 1000+ lines OpenAPI specification of your API and ask yourself: <strong>do I trust this?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*4n8_V1wEXvhdKp-O.jpg" /><figcaption>Me looking at any OpenAPI specification</figcaption></figure><h3>Let the hunt begin</h3><h4>Basic validation</h4><p>The first thing to do is to check if your OpenAPI spec is syntactically valid. For example by using <a href="https://editor.swagger.io/">https://editor.swagger.io/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDzoOAarGfdgBuWeMUTCQw.png" /><figcaption>Not off to a great start</figcaption></figure><h4>Swagger 2.0 vs OpenAPI 3.0 vs OpenAPI 3.1</h4><p>One common mistake when writing OpenAPI specifications by hand (or using custom code) is mixing the syntax from one of the three versions of OpenAPI.</p><ul><li><strong>swagger 2.0</strong>: the “legacy” version</li><li><strong>openapi 3.0</strong>: the most-used version, with a new structure and a schema syntax closer to JSONSchema</li><li><strong>openapi 3.1</strong>: the latest one, with schema declared using a custom JSON Schema <a href="https://json-schema.org/understanding-json-schema/reference/schema#declaring-a-dialect">dialect</a> (so JSON Schema + some custom properties).</li></ul><p>As an example, let’s see how each version handles describing a “nullable” property:</p><pre>#swagger 2.0:<br>#❌ nullable are not officially supported<br>#but you can use the &#39;x-nullable: true&#39; extension understood by most tools<br>MyData:<br>  properties:<br>    myNullableProp:<br>      type: string<br>      x-nullable: true <br><br>#openapi 3.0:<br>#nullable is officially supported with the &#39;nullable: true&#39; attribute<br>MyData:<br>  properties:<br>    myNullableProp:<br>      type: string<br>      nullable: true<br><br>#openapi 3.1:<br>#use the JSONSchema syntax, no more &#39;nullable: true&#39;<br>#instead &#39;type&#39; accept a list of values, including &#39;null&#39;<br>MyData:<br>  properties:<br>    myNullableProp:<br>      type: <br>        - string<br>        - null</pre><p>Looking back at the screenshot of the failing specification, we see that the specification is declared as swagger: &#39;2.0&#39; but seemed to use an OpenAPI 3.1 nullable declaration (type: &#39;null&#39;).</p><h3>One-shot validation with Prism</h3><p>Once the specification is syntactically correct, you just need to “validate” that what your API accepts and returns is as described in the specification: Same path, same status code, matching payload schema.</p><p>Doing that by hand is time-consuming and error-prone, so I suggest using a validation proxy. For example: <a href="https://github.com/stoplightio/prism">stoplightio/prism</a> (Prism isn’t just a validation proxy, but we will focus on validation today)</p><p><a href="https://github.com/stoplightio/prism">GitHub - stoplightio/prism: Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.</a></p><p>Start Prism by providing your OpenAPI specification file (or URL to it) and your API’s server address and make some calls through the exposed localhost proxy. Prism will passively validate each call and output the errors.</p><p>Here is an example using the classic <a href="https://petstore3.swagger.io/">petstore</a> API.</p><pre>$ npm install -g @stoplight/prism-cli<br>$ prism proxy petstore.yaml https://petstore3.swagger.io/api/v3<br>...<br>[CLI] ► start Prism is listening on http://127.0.0.1:4010</pre><pre>//$ curl -s &#39;GET&#39; &#39;http://127.0.0.1:4010/pet/1234&#39; -H &quot;api_key:secret&quot; | jq<br>{<br>  &quot;id&quot;: 1234,<br>  &quot;name&quot;: &quot;good boy&quot;,<br>  &quot;category&quot;: {<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Dogs&quot;<br>  },<br>  ...<br>}</pre><pre>[HTTP SERVER] get /pet/1234 i info Request received<br>[PROXY] i info &gt; Forwarding &quot;get&quot; request to https://petstore3.swagger.io/api/v3/pet/1234...<br>[PROXY] i info The upstream call to /pet/1234 has returned 200<br>[PROXY] i info &lt; Received forward response</pre><p>All good, no error found✅.</p><p>So let’s add a typo in the OpenAPI specification and redo our call.</p><pre>Pet:<br>  type: object<br>  properties:<br>    id:<br>--    type: integer<br>++    type: string<br>    name:<br>      type: string<br>    ...</pre><pre>[VALIDATOR] × error Violation: <br>response.body.id Response body property id must be string</pre><p>This time Prism displays an error, as expected. You can see the type of error (id must be string) and the JSON path of the property that failed (response.body.id).</p><h4>Prism at scale</h4><p>In 2023, we discovered typing issues on a few of our endpoints. We quickly fixed the corresponding OpenAPI specifications and decided to audit all our 200+ endpoints to see if other errors were hiding in the corners.</p><p>We used Prism for this analysis, allowing us to move faster and more confidently. We never found a false-negative or false-positive coming from Prism, so: <strong>good job Prism</strong>.</p><p>But, even with Prism, this was not painless.</p><h3>How to make your validation meaningless</h3><p>Most of Criteo’s endpoints follow a common response pattern that allows to return a mix of data , errors and/or warnings(It’s a bit similar to <a href="https://jsonapi.org/format/#document-structure">JSON:API</a>). So most of our endpoints use a C# generic class that contains data, errors, and warnings properties. The autogenerated schema looks a bit like this:</p><pre># A &#39;Criteo style&#39; response schema<br>MyResponse:<br>  type: object<br>  properties:<br>    data: <br>      type: ... #depends on the actual endpoint<br>    errors:<br>      type: array<br>      items: ... #the common error object<br>    warnings:<br>      type: array<br>      items: ... #the common error object</pre><p>Using Prism (or even a JSON Schema validator), let’s validate a few examples of responses against this schema.</p><pre>//response with data ✅<br>{<br>  &quot;data&quot;: {<br>     &quot;id&quot;: 1234,<br>     &quot;name&quot;: &quot;Bob&quot;<br>  }<br>}<br><br>//response with errors✅<br>{<br>  &quot;errors&quot;: [<br>     {<br>       &quot;message&quot;: &quot;oups&quot;<br>     }<br>   ]<br>}<br><br>//response with a typo in &quot;datta&quot;<br>//should be invalid, right?<br>//but the validator does not complains ✅<br>{<br>  &quot;datta&quot;: {<br>     &quot;id&quot;: 1234,<br>     &quot;name&quot;: &quot;Bob&quot;<br>  }<br>}<br><br>//wait, what? ✅<br>{<br>  &quot;wait&quot;: &quot;what?&quot;<br>}<br><br>//please, make it stop ✅<br>{<br>  &quot;please&quot;: [<br>    &quot;make&quot;, &quot;it&quot;, &quot;stop&quot;<br>  ]<br>}<br><br>//what have we done?! ✅<br>{<br>  &quot;what&quot;: {<br>    &quot;have&quot;: {<br>       &quot;we&quot;: &quot;done?!&quot;<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*fIkURo2xPwadw4KU.gif" /></figure><p>The problem is this schema is not constraining enough. None of the properties are required and, by default<strong>, an OpenAPI schema accepts additional properties</strong>.</p><p>This may seem surprising, but this enables SDKs built against a given version of your specification to gracefully discard new properties you may add later (instead of throwing an error). In other words, it makes your SDKs <strong>forward-compatible</strong> for property additions.</p><p>So, <strong>if nothing is required and additional properties are accepted, then almost anything is valid.</strong></p><p>To fix that, you could write a fancier schema:</p><pre>#a &quot;better&quot; schema<br>MyResponse:<br>  type: object<br>  properties:<br>    data:<br>      type: ...<br>    errors:<br>      type: array<br>      items: ...<br>    warnings:<br>      type: array<br>      items: ...<br>  additionalProperties: false #no additional props<br>  oneOf: #either just data, or data + warning or just errors<br>  - anyOf:<br>    - required: [data]<br>    - required: [data, warnings]<br>  - required: [errors]</pre><p>But this requires a good understanding of OpenAPI’s syntax, and you will most likely have to write custom adapters if you have a code-first approach. And, there are few chances that your SDK or documentation generator will play nice with this.</p><p>You could also have per-status code schemas: 2xx = required data + optional warnings, 4xx and 5xx = required errors, and nothing else.</p><p>But the simplest way is to add additionalProperties: false on each schema and sub-schema. But this would break the forward compatibility of the SDKs you generate. So you could do that <strong>just for the specification you use for the validation</strong>.</p><h3>Know your domain</h3><p>Surprisingly, most of the work was not to set up Prism, investigate the errors we found, or tweak the additionalProperties. It was to find good input examples for our 200+ endpoints.</p><p>Especially when an endpoint is part of a complex flow or can have a wide range of responses. For example, a simple enum can be difficult to validate in a black-box approach: what input and/or state do you need to return each possible value? And what business edge case has you missed that could return an undocumented value?</p><p><strong>So gather some domain experts by your side to generate good test cases</strong>.</p><h3>Live contract testing</h3><p>So, we have tested all our endpoints and fixed a few bugs. But nothing prevents new mistakes from appearing (or even re-appearing). Are we condemned to retest everything each month? Each week?</p><p>What would be ideal is an always up-to-date set of input examples, representing our most complex flow and edge cases. Well, that’s production, right?</p><p>Prism documentation mentions <a href="https://github.com/stoplightio/prism/blob/master/docs/guides/03-validation-proxy.md#live-contract-testing">live contract testing</a>, but mostly focuses on non-production environments and discourages using Prism in production (for performance reasons). And proxying your customers’ authenticated calls through a third-party tool raises some concerns.</p><p>We gained some experience with this manual analysis, and we use a custom-built C# API gateway. So why not build a custom validation middleware?</p><p>What do we need:</p><ul><li>The OpenAPI specification(s) to validate against ✅</li><li>A way to easily read and manipulate the specification. We can use <a href="https://github.com/microsoft/OpenAPI.NET">microsoft/OpenAPI.NET</a> ✅</li><li>Some <a href="https://swagger.io/docs/specification/v3_0/data-models/keywords/">rules</a> to transform a request/response schema into a proper JSONSchema ✅</li><li>Dynamically making our schema more validatable (no additional properties) ✅</li><li>And finally a JSON schema validator, like <a href="https://github.com/RicoSuter/NJsonSchema">RicoSuter/NJsonSchema</a> ✅</li></ul><p>There are also some non-functional requirements (good performance, not logging credentials, passive validation, …) and you need some logic to validate the “non-JSON Schema” stuff (status code, parameters, …).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*geR_RzuIrxFwLhVR" /><figcaption>Our live validator ❤️</figcaption></figure><p>And after letting it run for a few days at a 1% sampling rate, we can dig into the result. We will focus on the previewversion, where new, potentially unstable, endpoints are released. So also where we expect to find more problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2Fv2lCnzyEZeWMeEkqGig.png" /><figcaption>Some preliminary result from our live validator</figcaption></figure><p>Mostly good, but we have some endpoints that are invalid on ~5% of the calls. That’s sad, but also exactly why we built this tool: <strong>finding edge cases more easily and continuously.</strong></p><p>Now we just have to roll up our sleeves and go fix some bugs🙂.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*4MwyIHh4llGs_W43.gif" /></figure><h3>What did we learn today?</h3><ul><li>Your version of OpenAPI matters</li><li>OpenAPI is complex, and no design-first or code-first approach will prevent your specification from being inaccurate</li><li>A lot of tools only partially support the whole OpenAPI feature set, so over-designing your specification may make it less effective at its original job: good SDKs and good docs</li><li>Beware of non-required props and allowed additional props by default</li><li><a href="https://github.com/stoplightio/prism">Prism</a> works well, but good test coverage requires domain expertise</li><li>You can build your own validation tool (if you have a good JSON Schema validation library at hand)</li></ul><p>Hopefully, you found this article interesting.</p><p>If you want to read more about how we built Criteo’s API, check my colleague Scott’s last article:</p><p><a href="https://techblog.criteo.com/building-criteo-api-what-weve-learned-b7f3e7b8d270">Building Criteo API, What We’ve Learned</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62677d43fb3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/criteo-engineering/can-you-trust-your-openapi-spec-a62677d43fb3">Can you trust your OpenAPI spec?🤨</a> was originally published in <a href="https://medium.com/criteo-engineering">Criteo Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postman: from local tests to our CD pipeline]]></title>
            <link>https://medium.com/criteo-engineering/postman-from-local-tests-to-our-cd-pipeline-670d31666e6?source=rss-475d24faa679------2</link>
            <guid isPermaLink="false">https://medium.com/p/670d31666e6</guid>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[concourseci]]></category>
            <category><![CDATA[postman]]></category>
            <dc:creator><![CDATA[Jean Baptiste Muscat]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 06:57:12 GMT</pubDate>
            <atom:updated>2023-06-29T06:57:12.632Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A new article in the Criteo DevXDays series. You can find all the articles about Developer Experience at Criteo <a href="https://medium.com/criteo-engineering/tagged/criteo-devxdays">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXBrWt36aIwRcer9WU57dA.png" /><figcaption>Generated with <a href="https://labs.openai.com/s/zPlqJ6IITyXqMUOcRlpt3K22">Dall-e</a> for this article</figcaption></figure><h3>API = API + network + dependencies + …</h3><p>As API developers, we can spend hours debating over which HTTP verb, status code, or parameter name to use. And then we release and the whole thing comes crashing down because of an obscure network problem that only exists in a multi-datacenter setup 🤷.</p><p>Unit and isolated tests are fast and useful, but at the end of the day, APIs are about moving data in or out of your systems, so you still need to perform full end-to-end tests. Let’s see how Postman can help us do that.</p><h3>Testing with Postman</h3><p><a href="https://www.postman.com/">Postman</a> is a desktop HTTP client that gives you full control over the shape of the request (which headers to set, which parameters, etc.) and displays the response (body and headers) and a plethora of metadata.</p><p>Especially useful is the “tests” tab, in which you can write JavaScript-based tests to validate the request and response of your query. Various functions and variables are provided and you can even use some NPM packages (for example, AJV to perform <a href="https://www.postman.com/postman/workspace/postman-answers/request/9215231-333ddae8-eb72-496d-9e45-6b49a87c7d09">JsonSchema validation</a> against the body).</p><p>Learn more about Postman tests in the official <a href="https://learning.postman.com/docs/writing-scripts/test-scripts/">docs</a> 📙.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eDVe3VKdWUAS0iAL65crWA.png" /><figcaption>An example of a test validating the status code and body of our token endpoint</figcaption></figure><h4>Collections</h4><p>Several queries can be regrouped in a “collection”, and you can share variables among them. For example, you can reuse an authentication token in several calls or extract a variable from the response body of one query and use it as a path parameter in another one. And you can run all queries in a collection at once, with a single click.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHIWXuJ--fY8r2iWiuFFLg.png" /><figcaption>Running all queries from a collection at once.</figcaption></figure><p>All the tests written for each query will also be run and included in the overall results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYdGBFJPn3rQTpiUHqBW-Q.png" /><figcaption>The result of a collection run.</figcaption></figure><h4>Sharing is caring</h4><p>By default, a collection lives in your Postman workspace. You can easily export it as a JSON file that can be imported by another user. Or you can leverage the robust <a href="https://learning.postman.com/docs/collaborating-in-postman/working-with-your-team/collaboration-overview/">collaboration </a>tools provided by Postman to share collections directly with your team.</p><h3>Automation with Newman</h3><p>Once your team starts to own several APIs, having to open Postman each time you want to quickly test an application after a deployment becomes tedious. So, a few years ago, we started to store our Postman collections directly in the git repository of the application they test.</p><p>This makes collections easy to find, as they are right next to the code. But it makes running the collection a slog; you have to git clone or pull and reimport the collection every time.</p><h4>Newman: The Postman CLI</h4><p>But what if, with a single command line, you could fetch and run a whole collection? Enter <a href="https://learning.postman.com/docs/collections/using-newman-cli/command-line-integration-with-newman/">Newman</a>, the official Postman CLI.</p><p>Simply install it (it’s an NPM CLI) and “run” your collection file. It will display a short summary of the execution, including how many tests have been executed and how many have failed.</p><pre>$ npm install -g newman<br>$ newman run sample-collection.json<br><br>Sample Postman Collection<br><br>→ A simple GET request<br>  GET https://postman-echo.com/get?source=newman-sample-github-collection [200 OK, 849B, 623ms]<br>  √  expect response be 200<br>  √  expect response json contain args<br><br>→ A simple POST request<br>  POST https://postman-echo.com/post [200 OK, 1.07kB, 290ms]<br><br>→ A simple POST request with JSON body<br>  POST https://postman-echo.com/post [200 OK, 1.18kB, 138ms]<br><br>┌─────────────────────────┬─────────────────────┬────────────────────┐<br>│                         │            executed │             failed │<br>├─────────────────────────┼─────────────────────┼────────────────────┤<br>│              iterations │                   1 │                  0 │<br>├─────────────────────────┼─────────────────────┼────────────────────┤<br>│                requests │                   3 │                  0 │<br>├─────────────────────────┼─────────────────────┼────────────────────┤<br>│            test-scripts │                   1 │                  0 │<br>├─────────────────────────┼─────────────────────┼────────────────────┤<br>│      prerequest-scripts │                   0 │                  0 │<br>├─────────────────────────┼─────────────────────┼────────────────────┤<br>│              assertions │                   2 │                  0 │<br>├─────────────────────────┴─────────────────────┴────────────────────┤<br>│ total run duration: 1387ms                                         │<br>├────────────────────────────────────────────────────────────────────┤<br>│ total data received: 2.13kB (approx)                               │<br>├────────────────────────────────────────────────────────────────────┤<br>│ average response time: 350ms [min: 138ms, max: 623ms, s.d.: 202ms] │<br>└────────────────────────────────────────────────────────────────────┘</pre><p>Even better, you can run a remote collection, for example, loaded directly from Github. No need to clone or pull. It’s always up-to-date😃.</p><pre>$ newman run https://raw.githubusercontent.com/postmanlabs/newman/develop/examp<br>les/sample-collection.json</pre><h4>Handling secrets</h4><p>Most of our APIs use authentication, so to test them we need some kind of credentials. The simplest way would be to add a set of IDs and passwords directly to the queries or as collection variables. But those would end up in the JSON file in the git repository⚠️.</p><p>Luckily, you can use a <a href="https://learning.postman.com/docs/collections/running-collections/working-with-data-files/">data file</a> when running a collection. It’s a simple JSON file containing an array of key-value pairs. Each key value is a variable that will be injected at run time into your collection.</p><p>For example, here this basic data file declares a single variable: <em>token</em></p><pre>[<br> { <br>   &quot;token&quot;:&quot;mySuperSecretToken&quot;<br> }<br>]</pre><p>When running the collection, a <em>{{token}}</em> variable will be available and usable in all queries. Learn more about variables and scopes on the Postman <a href="https://learning.postman.com/docs/sending-requests/variables/">docs</a>📙.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T56doKyvgG1edTc9urC71Q.png" /><figcaption>A query using a {{token}} parameter</figcaption></figure><p>And here is how to run a collection with Newman, using a data file:</p><pre>$ newman run sample-collection.json --iteration-data data.json</pre><p>We ended up regrouping all our API testing secrets in a single data.json file that all team members would store locally. This means that no secret would ever be present in the Postman collections, making them safe to store in the git repositories.</p><h4>Scripting</h4><p>And for convenience, we wrapped it all in a bash function that takes the repository ID as an argument, checks that the repository exists and contains a collection file in the usual spot, and runs the collection with Newman.</p><pre>#Run the deployment Postman collection with Newman<br>#Parameter: the name of the repo (ex: &quot;criteo-api/exam-oauth&quot;)<br>apiTest() {<br> project=$1<br> <br> #Validate that the repo exists<br> repoUrl=&quot;https://raw.githubusercontent.com/${project}&quot;<br> curl -silent -f -L $repoUrl -o /dev/null<br> exit_status=$?<br> if [ $exit_status != 0 ]<br>  then<br>   echo &quot;Repo for project ${project} does not exist&quot;<br>   return 1<br> fi<br> <br> #Validate that the collection exist<br> collectionUrl=&quot;${repoUrl}/deployment/postman_collection.json&quot;<br> curl -silent -f -L $collectionUrl -o /dev/null<br> exit_status=$?<br> if [ $exit_status != 0 ]<br>  then<br>   echo &quot;Test collection for project ${project} does not exist&quot;<br>   return 1<br> fi<br><br> #Validate that data.json exists<br> dataFile=~/deployment-test/data.json<br> if [ ! -f &quot;$dataFile&quot; ]; then<br>  echo &quot;Local data file does not exist ($dataFile).&quot;<br>  return 1<br> fi<br> <br> #Run collection with newman<br> newmanCommand=&quot;newman run ${collectionUrl} --iteration-data ${dataFile}&quot;<br><br> ${newmanCommand}<br>}</pre><p>Now running the Postman collection for the repository can be done with this simple command</p><pre>$ apiTest my/repository</pre><h3>Integrating with Concourse</h3><p>Last year, we started moving to a full CI/CD pipeline, with every application automatically deployed weekly. We also wanted to leverage the Postman test collections we had already created.</p><p>Our CI/CD pipeline is <a href="https://concourse-ci.org/">Concourse</a>. Everything is a container in Concourse, so adding a custom step means providing a dedicated container for it. We could create a Docker container that has Newman installed and use it to run the collection from our repository during deployment. Easy. But we end up with the same problem regarding secrets as before: we don’t want to have the secrets in the container itself.</p><p>After some deliberation, we decided to create our own application that would be in charge of fetching the collection from other repositories and the secrets from our Vault instance (our secrets repository).</p><p>The good thing is it simplifies the integration with Vault and makes “running a scenario” a simple HTTP call. Meaning it can be easily done by Concourse, but also by a human or a scheduling system. And we are free to extend it with additional capabilities later. For example, we could validate that the API tested by a collection satisfies the OpenAPI Specification of this very API (this will be the topic for a future article 😉).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/0*2m1uaCME_xuHf1Qv" /><figcaption>C4 diagram of the proposed architecture</figcaption></figure><h4>Mixing C# and Node.js?</h4><p>As most of our internal applications are written in C#, the core application would also be written in C#. But <strong>how do you run a Postman collection from within a C# application</strong>?</p><p>The simplest way is to install Newman in the same container as the C# application and perform system calls. But I don’t like having two heterogeneous technologies in the same container, especially when one of them will be making calls to a lot of our APIs, and the other one has access to our secret repository.</p><p>In my ideal world, someone would have built a “Newman-as-a-web-service” that exposes a simple stateless <em>POST /run</em> endpoint to run a collection (with an optional data file). Well, nobody had, but this didn’t seem very complicated, as Newman exposes its own<a href="https://github.com/postmanlabs/newman#api-reference"> internal API</a> to be used inside a Node.js application.</p><h4>Newman-Server</h4><p>And that’s how <a href="https://www.npmjs.com/package/newman-server">newman-server</a> is born. A simple server that executes Postman collections on demand.</p><pre>$ npm install -g newman-server<br>$ newman-server<br>Server started on port 8080</pre><p>It has a lightweight front end to play with it but is mostly intended to be used as a backend only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*4lptWqqS0VzU2nEePsxG5A.png" /><figcaption>The barebone UI of newman-server</figcaption></figure><h4>Final integration</h4><p>With everything in place, we can add our validation step in Concourse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TAXSlgS4QE5Sew63ekgcQ.png" /></figure><p>The step outputs a synthetic version of the Newman JSON report, discarding any request or response bodies (to prevent leaking secrets), but keeping a per-assertion status, so it’s easy to find what part of the test actually went wrong:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O0FOCY6K8-1RdBaPF2Y5dA.png" /><figcaption>Looks like we have an authentication problem 😔</figcaption></figure><h3>Conclusion</h3><p>I hope you liked this quick dive into how we use Postman to test our APIs. This topic was part of our internal Developer Experience conference cycle, and you can find a video of the associated presentation here.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeC8naWv6UQo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeC8naWv6UQo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeC8naWv6UQo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fca23c204baf60f79946f622f2c84d0e/href">https://medium.com/media/fca23c204baf60f79946f622f2c84d0e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=670d31666e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/criteo-engineering/postman-from-local-tests-to-our-cd-pipeline-670d31666e6">Postman: from local tests to our CD pipeline</a> was originally published in <a href="https://medium.com/criteo-engineering">Criteo Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building better APIs with chatGPT]]></title>
            <link>https://medium.com/criteo-engineering/building-better-apis-with-chatgpt-9d3350beaf51?source=rss-475d24faa679------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d3350beaf51</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[open-api]]></category>
            <dc:creator><![CDATA[Jean Baptiste Muscat]]></dc:creator>
            <pubDate>Wed, 17 May 2023 06:47:21 GMT</pubDate>
            <atom:updated>2024-04-11T15:39:06.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>Can LLMs help us build better APIs?</h3><p>ChatGPT is here and it’s already quite good at understanding and writing code. But it can also understand APIs. In fact, that’s how chatGPT <a href="https://platform.openai.com/docs/plugins/introduction">plugins</a> work: you simply provide your API’s <a href="https://www.openapis.org/">technical specification</a> and chatGPT will infer how to use it.<br>So, what does it mean for API developers? Can GPT help us build better APIs?</p><blockquote><strong>Disclaimer:</strong> in this article, I will mainly focus on <strong>GPT3.5</strong>, as it’s the cheapest, most widely available model. On specific occasions, I will switch to <strong>GPT4</strong>. <br>I’m also focusing only on REST API, as this is my main domain of expertise. Some knowledge of <a href="https://www.openapis.org/">OpenAPI</a> is a plus.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRh2z8D-sepaBUaE-gUHBA.png" /><figcaption><a href="https://labs.openai.com/s/V9eNthsYs7BEKAOa05z997B6">Dall-e generated</a> for this article</figcaption></figure><h3>Key findings</h3><ul><li><strong>To analyze an API, import the OpenApi specification into chatGPT.</strong><br>✅ OpenApi specifications are big. Minify them to not waste tokens.<br>❌ Even minified, many APIs will simply not fit.</li><li><strong>Use GPT as a use-case validator to ensure your API fulfills human-expressed requirements.<br></strong> ✅ This will make sure your API is user-friendly.<br>✅ This makes your API inherently GPT-ready.</li><li><strong>GPT can help you design more consistent APIs.</strong><br>✅ GPT is good at improving summaries and descriptions.<br>✅ GPT can check if your endpoint paths follow standards.<br>✅ GPT can identify if your CRUD API is missing any endpoints.<br>❌ GPT3 struggles with schema and type inconsistencies. False positives are a problem. GPT4 is better but slower and not perfect.</li><li><strong>GPT can help you write technical guidelines.</strong><br>❌ GPT tends to lose some of the implicit contexts when rewording a technical document. Be careful when rewriting technical documents.<br>✅ Use GPT as an example generator for your guidelines. If the examples are good, this means your guidelines are complete.</li></ul><h3>Why I care</h3><p>I work on <a href="https://developers.criteo.com/">Criteo’s external API</a>, both in the team responsible for our API Gateway and as a member of the internal API Guild. It’s the Guild’s responsibility to ensure consistency across our 200+ endpoints while interacting with the 20+ internal teams that each work on a subset of these endpoints.</p><p>Maintaining quality and consistency across our APIs is a challenging task. Over the years, we have added layers of automated checks, custom guidelines, and manual processes. But this is still an ongoing battle.</p><p>So, given how easily chatGPT seems to understand APIs, I’ve been eager to see if it could help us.</p><h3>1. Importing your API into chatGPT</h3><h4>So many tokens</h4><p>To provide an “API” to chatGPT, you essentially paste the <a href="https://www.openapis.org/">OpenAPI Specification</a> (aka OAS aka Swagger). An OAS describe all the endpoints in an API, their inputs, and outputs. So OASs tend to be quite large. For example, the classic <a href="https://petstore3.swagger.io/">PetStore API</a> is 1,200 lines long.</p><p>But GPT (as any <a href="https://en.wikipedia.org/wiki/Large_language_model">LLM</a>) can only work on a small amount of text at a time. The limit is expressed in “tokens”. <a href="https://platform.openai.com/docs/models/gpt-3-5">GPT3.5 turbo</a> can process up to 4k tokens. <a href="https://platform.openai.com/docs/models/gpt-4">GPT4</a> bumps that to 8k (or even 32k with a specific variant).</p><p>Using OpenAI’s <a href="https://platform.openai.com/tokenizer">online tokenizer</a>, we can find the token count for a given input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*cgckOhoYRUM4sHwAtK2_6g.png" /><figcaption>A simple phrase tokenized</figcaption></figure><p>So, let’s fetch the OpenApi Specifications of various APIs and see how they fare.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9bbe40acf237a383269527b23d96806/href">https://medium.com/media/e9bbe40acf237a383269527b23d96806/href</a></iframe><p>Well, many APIs are simply too big to fit in current GPTs contexts. That’s why OpenAI recommends striping down your API when building chatGPT Plugins.</p><h4>JSON vs YAML vs minified</h4><p>OAS can be written in JSON and YAML. Does this have an impact on the number of tokens? Does minification (stripping white spaces and line breaks) have an impact?</p><p>Let’s try that on the <a href="https://petstore3.swagger.io/">PetStore API</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42ea99e04ef5c627dc9000482a54681a/href">https://medium.com/media/42ea99e04ef5c627dc9000482a54681a/href</a></iframe><p><strong>Switching to YAML reduces the tokens by ~40%, but minification is the real winner.</strong></p><h4>In chat usage</h4><p>The tokens limit for GPT is the total “context” that it can handle. To create the illusion of a discussion with chatGPT, OpenAI does something quite simple, it feeds back the previous questions and answers in GPT’s context each time you ask something.</p><p>So OpenAI has added a stricter limit in the chat UI, only allowing “short” questions. If you try to send the minified PetStore OAS, you’ll get this message. So only small APIs can be analyzed in the chat UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*C84JNoBfISsAp1UGr3R--A.png" /></figure><h4>Vector databases</h4><p>For a large amount of text, vector databases (like <a href="https://www.pinecone.io/learn/vector-database/">Pinecone</a>) can be used to inject only the relevant part of a lengthy text into a GPT query. This is common for creating bots that answer questions about a product’s documentation.<br>It may be possible to leverage that to dynamically inject only the relevant part of a big API’s OAS for a given question. But I‘m not sure how this could be done, as an OAS is a single document, with a lot of inner references. <br>That’s a topic for another time.</p><h3>2. A simple ChatBot API</h3><p>For the rest of the article, I’ll use a simple API designed for the occasion. I don’t want to use an existing API, as chatGPT may have seen it during its training and this could pollute its answers.⬇️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*WTDT8qtAavKGOCJ6EVgpBg.png" /><figcaption>ChatGPT already knows about the PetStore API</figcaption></figure><p>So, I’ve created a basic API that manipulates chatbots. It’s poorly written by design 😉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GizOo2BM9eH--R6uGyr4Q.png" /><figcaption><a href="https://gist.github.com/ouvreboite/389c0aca5550677c2eb244ce5529f75c">https://gist.github.com/ouvreboite/389c0aca5550677c2eb244ce5529f75c</a></figcaption></figure><p>Before going further, let’s ensure chatGPT is able to understand it.</p><pre># GPT Prompt 🤖<br><br>Extract the endpoints from the API and return a table containing <br>the endpoints and their summary. <br>The response should be in markdown format.<br>Return only the table.<br><br>The API specification:<br>&#39;&#39;&#39;<br>{{minifiedOAS}}<br>&#39;&#39;&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*q90pY9FaVNgK5qfmVzZZsg.png" /><figcaption>ChatGPT correctly lists the API endpoints.</figcaption></figure><p>Perfect. We can start.</p><h3>3. Does my API actually fulfill my client’s needs?</h3><p>You know the story. A client expresses some needs, which are evaluated by the business analyst, prioritized, refined during grooming, then somehow implemented. And it’s up to the developer, that just spent two weeks on implementation to fill in the OpenAPI Specification. That’s how you end up with a bunch of poorly defined keywords or internal domain entities in your API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgTKciSNxKG-DTUQD5aZcw.png" /><figcaption>Slightly adapted by me</figcaption></figure><p>But, your API is intended to be used by external users/developers. It should make sense to them, not to you. In other words:</p><p><strong>How do you know if your API makes sense for someone from the “outside”, if everybody involved in the development of the API is from the “inside”?</strong></p><p>Well, ask chatGPT.</p><h4>Use case example</h4><p>Here is a use case that the API should fulfill: <em>“I want to find the publicly available bots and use one to get an answer to my question.”</em></p><p>During the design of the API, I added a query parameter on the <em>GET /chatbot</em> endpoints to filter them based on their availability. So I expect GPT to leverage that. Let’s see how it goes:</p><pre># GPT Prompt 🤖<br><br>With this API, can you fulfill the following use case ?<br>Use case:<br>&quot;I want to find the publicly available bots <br>and use one to get an answer to my question&quot;<br><br>Answer simply by &#39;yes&#39; or &#39;no&#39;. If you are unsure, answer &#39;Unsure&#39;.<br>If you think this user demand can be fulfilled, <br>list the endpoints that you would use to fulfill it.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*LYsBeHu24XvKd_nHQPMGsg.png" /><figcaption>ChatGPT correctly considers that the use case can be fulfilled.</figcaption></figure><p>GPT considers the use case valid and uses the endpoints as intended.</p><h4>Incorrect use case example</h4><pre># GPT Prompt 🤖<br><br>With this API, can you fulfill the following use case ?<br>Use case:<br>&quot;I want to find the cheapest chatbot&quot;<br><br>Answer simply by &#39;yes&#39; or &#39;no&#39;. If you are unsure, answer &#39;Unsure&#39;.<br>If you think this user demand can be fulfilled, <br>list the endpoints that you would use to fulfill it.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*9EYMoim-161Bja1uvemvFw.png" /><figcaption>ChatGPT correctly considers that the use case cannot be fulfilled.</figcaption></figure><p>GPT correctly assesses that this use case is not fulfilled by the API (there no pricing information in the API).</p><h4>Benefits</h4><p>I see three main benefits of using GPT here</p><ol><li><strong>It tightens the feedback loop</strong> by matching together two things that are traditionally opposed: human-expressed requirements and technical specifications. You can catch some improper designs or unsatisfied user requirements earlier.</li><li><strong>It acts as a “neutral” assessor</strong>. It can be hard to hear a fellow developer say that the API you’ve worked on for weeks “doesn’t make sense”. Relying on a language model alleviates that.</li><li><strong>It ensures your API is “GPT Ready”</strong> because you’ll have ensured that GPT understands it correctly. So implementing a GPT plugin will go smoothly.</li></ol><h3>4. Is my API complete? Is it consistent?</h3><p>We know that GPT understands how to use the API. But can we also use it to improve the consistency of the API?</p><h4>4.1. Better summaries</h4><pre># GPT Prompt 🤖<br><br>Extract the endpoints from the API and return a table containing <br>the endpoints and their summary and an alternative summary. <br>The alternative summaries should be consistent in style and syntax <br>and start with a verb.<br>The response should be in markdown format.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*ua6MXooAK4zTSo-o4B4-Lw.png" /><figcaption>Alternative summaries.</figcaption></figure><p><strong>Quite good, but not perfect.</strong> For example, the summary “<em>Get a list of all available chatbots</em>” may be misleading considering that this endpoint has a parameter to filter out chatbots based on their public/private availability.</p><p>Personally, I often suffer from “white page syndrome” when filling up descriptions and summaries. But I have no problem nitpicking on one, once written. So with GPT, here is my process:</p><ol><li>Write the most “to the point” summary possible.</li><li>Have GPT propose a nicer summary, consistent with the rest of the API.</li><li>Manually adjust the summaries, if needed.</li></ol><h4>4.2. Better paths</h4><pre># GPT Prompt 🤖<br><br>Extract the endpoints from the API and return a table containing <br>the endpoints and their summary and an alternative path. <br>The alternative path should follow the REST guidelines.<br>The response should be in markdown format.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*h3_5SegoFD56gFikFthwvQ.png" /></figure><p>GPT correctly updated the <em>/chatbot</em> path to <em>/chatbots</em>. But it also changed the <em>/generate-response</em> to <em>/responses</em>, which may be good, or not, depending on your views on action vs resources endpoints 😉.</p><p><strong>GPT can be used to improve the consistency of your endpoints path. But this mostly works for resource-related endpoints.</strong></p><p>Let’s fix the OAS and move on.</p><h4>4.3. CRUD complete</h4><p>A lot of the APIs we write are CRUD by nature. And as API users, we also expect some level of CRUDeness. For example, if we see a GET, POST, and DELETE endpoint, we may expect a PUT endpoint.</p><pre># GPT Prompt<br><br>Are them some endpoints missing to offer a CRUD API for the ChatBot entity?<br>If you don&#39;t know, simply answer &quot;I don&#39;t know&quot;.<br>If there are endpoint missing, list them in a table containing the missing endpoints and a proposed summary.<br>The response should be in markdown format.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*liiicGlsX4hr_Q8L6AOXzA.png" /></figure><p>Obviously, all APIs are not intended to be CRUD. But, sometimes, we really intend to build a CRUD API, and GPT can be there to remind us of some forgotten endpoints :)</p><p><strong>GPT can be used to suggest missing endpoints, that your users could expect.</strong></p><h4>4.4. Finding schema and type discrepancies</h4><p>Let’s ask something more open now.</p><pre># GPT Prompt 🤖<br><br>Please list the discrepancies you can find between the parameters <br>of the endpoints and the schema of the entities returned by those endpoints. <br>Pay close attention to incorrect names and inconsistent types.<br><br>If there are no discrepancies, simply return: &quot;LGTM!&quot;</pre><p>I’ve intentionally created a mismatch between the availability parameter in <em>GET /chatbots</em> (that only contains <em>public </em>and <em>private</em>) and the availability field in the <em>ChatBot</em> schema (that contains <em>public</em>, <em>private</em><strong>, </strong>and <em>on-demand</em>). So I hope GPT can detect that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*vG1RGcUbFL6-UR6_QQFN6Q.png" /><figcaption>Initial response</figcaption></figure><p>Hmm... GPT detected an unintentional typo. Which is quite good, as it is able to match a parameter and a property despite the misspelling. But it did not find the enum problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*xWKaHGKS5BQQGvDtw_DaZw.png" /><figcaption>Second response</figcaption></figure><p>By regenerating the response, GPT finds the missing <strong>on-demand</strong> enum value. But it says nothing about the typo. In fact, it silently “fixes” it. Regenerating, again and again, yields a variety of answers. Most of them detect the typo, some of them detect the missing enum, and a few of them detect false positives.</p><p>Let’s fix the OAS and ask again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*1Rl7v13Ni79VJa7867VCUA.png" /></figure><p>Hold on! Now GPT has discovered a bunch of new discrepancies that it did not detect before. And most of those are plainly false. It seems GPT has some problems fully understanding property types in nested schemas. The only valid one would be 3), but it’s not really what I asked for.</p><h4>Can GPT4 do better?</h4><p>Maybe this question is a little too complex for GPT3. Let’s try again but with GPT4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*gwCIWXtggzjEtn9Hc5sSSg.png" /></figure><p>With the initial OAS, GPT4 find the two problems (typo in the <em>‘availabily</em>’ name, and missing the ‘<em>on-demand</em>’ enum value). But the response is still unstable: asking again will sometimes result in only the typo being detected. Overall, the quality of the response has improved.</p><p>Once the OAS is fixed, GPT4 is more stable and does not return false positives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*HW3-YqvD5O5KzHhWcKH-Sw.png" /></figure><p>An important point: GPT4 takes almost 30s to generate the response using GPT4. GPT3 only takes ~5s.</p><h4>Interesting, but…</h4><p>I’m both impressed and disappointed. With this kind of open question, the instability of GPT’s responses is starting to show. False positives are also a big problem because it took me way longer to ensure that they were actually false positives than it took GPT3 to falsely “detect” them.</p><h3>5. Improving custom guidelines</h3><p>As mentioned before, Criteo’s API Guild has created a set of guidelines for our internal developer. Those tend to be quite long and are mostly reviewed by the Guild itself or, at minimum, by people that are very familiar with API development. It’s quite difficult to know when a guideline is too verbose or, inversely, relying too much on the reader&#39;s own knowledge of standard API practices.</p><p>For example, here is one of our guidelines regarding Response Bodies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ab24a5a0b3f7cc0f2fd2540c2608ae6/href">https://medium.com/media/6ab24a5a0b3f7cc0f2fd2540c2608ae6/href</a></iframe><h4>5.1. Basic test</h4><p>Let’s start by feeding the guidelines to GPT and ask a few questions.</p><pre># GPT Prompt 🤖<br><br>Here are custom API guidelines, written in markdown.<br>Answer the following requests:<br>1. Do you understand those guidelines?<br>2. Provide a short summary of the guidelines. Answer in 30 words max.<br>3. In the context of those guidelines, <br>   what is the difference between an entity and a value object? <br>   How does their JSON representation differ? Answer in 20 words max.<br><br>The guidelines:<br>&#39;&#39;&#39;<br>{{guidelines}}<br>&#39;&#39;&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*M4T35BSzG94u6MapU8QfxA.png" /></figure><p>That’s a good sum-up.</p><h4>5.2. Rewording guidelines.</h4><p>Those guidelines are quite technical. So any change in wording can have a big impact. And there lies the problem: knowing those guidelines, I know they could benefit from some surface-level rewording, but also from more structural change.</p><p>But both GPT3 and GPT4 fail to keep the technical meaning of the phrases intact, and even more while restructuring a whole document.</p><p>For example, using this conservative prompt:</p><pre># GPT Prompt 🤖<br><br>Please reword the following markdown document. <br>Do not change its meaning, simply improve the wording. <br>Do not change the keyword MUST, SHOULD, SHOULD NOT, and MAY. <br>Keep the links in. <br>If you are uncertain about a specific part, ask me. <br>If you have no questions, simply output the updated document.<br><br>The document:<br>{{document}}</pre><p>Let’s look at the result for one of the phrases.</p><pre># Initial phrase<br>A response body is part of the output of an operation, <br>along with the status and headers. <br><br># GPT3 rewording<br>A response body is returned by the server as part of an operation, <br>alongside the status and headers. <br><br># GPT4 rewording<br>The response body forms a portion of an API operation&#39;s output, <br>alongside status and headers. </pre><p>The changes are small, but they are meaningful. GPT3 no longer uses <em>output</em>, which has a specific meaning for an API. And GPT4 decided to use <em>a portion </em>instead of <em>a part</em>, which is not really clearer.</p><p><strong>GPT can be used to reword technical documents but be careful as it may lose some of the implicit domain keywords, especially if those keywords are also common words.</strong></p><h4>5.3. Generating guidelines examples</h4><p>One aspect where I think GPT shines is in generating examples.<br>For each of our guidelines, we manually write JSON examples. But examples can be incorrect, or outdated, and if your user must rely on your example to understand the rules, maybe it’s because the rules are not so well written.</p><p>So, let’s ask GPT to generate the example, using only the corresponding guidelines and a textual description of what the example should showcase. If it succeeds, the guidelines are clear enough to be understood.</p><p>I’ll try to replicate one of our manually crafted examples, by simply describing it to GPT.</p><pre># GPT Prompt 🤖<br><br>Create a valid JSON example for the following guidelines.<br>The example should be a response body of a marketing campaign entity <br>with an id 1234<br>and with the attributes &#39;name&#39;, &#39;startDate&#39;, &#39;endDate&#39;, &#39;status&#39;. <br>It should have a relationship to an advertiser <br>using the link &#39;retail-media/advertisers/123&#39;.<br>It should have a relationship to three budgets of ids 9991, 9992 and 9993.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*UdFue8fbP8BK5cm09pbGZQ.png" /><figcaption>Example written by GPT</figcaption></figure><p><strong>That’s very good!</strong> The JSON is structurally valid and follows the custom guidelines and the example description provided in the prompt. In fact, it’s almost identical to the manually crafted example, with only minor differences in areas not specified by the guidelines.</p><h3>Conclusion</h3><p>GPT’s understanding of an API structure is not perfect. Its unreliability and tendency to hallucinate mean it’s not ready to be used as an automated test. But it’s promising, and I think it can already be useful in assisting developers less familiar with API design.</p><p>I’m impressed by GPT&#39;s ability to act as an “external” developer, allowing me to predict how others can (or cannot) use an API to perform specific actions.</p><p>But, the main problem is the limited context, that prevents GPT from analyzing anything more than a handful of endpoints. So, I’m hoping that LLMs with higher token limits will become widely available soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d3350beaf51" width="1" height="1" alt=""><hr><p><a href="https://medium.com/criteo-engineering/building-better-apis-with-chatgpt-9d3350beaf51">Building better APIs with chatGPT</a> was originally published in <a href="https://medium.com/criteo-engineering">Criteo Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Rate-Limiting Algorithms]]></title>
            <link>https://medium.com/criteo-engineering/distributed-rate-limiting-algorithms-a35f7e24783?source=rss-475d24faa679------2</link>
            <guid isPermaLink="false">https://medium.com/p/a35f7e24783</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[criteo]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Jean Baptiste Muscat]]></dc:creator>
            <pubDate>Thu, 24 Feb 2022 11:26:17 GMT</pubDate>
            <atom:updated>2022-03-02T07:53:58.267Z</atom:updated>
            <content:encoded><![CDATA[<p>Which tools and algorithms can be used to design a distributed rate-limiting system?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MJUV5onWvk_OybwI" /><figcaption>Photo by <a href="https://unsplash.com/@mrthetrain?utm_source=medium&amp;utm_medium=referral">Joshua Hoehne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Criteo is one of the biggest ad-tech players. As the advertising market is ever-evolving, a big focus at Criteo in the past years has been to improve our APIs, to offer our clients better programmatic access to our services.</p><p>With the increased adoption and usage of those new APIs, it was clear that we needed to implement some kind of rate-limiting, to ensure that all clients have equal access to our resources and protect our APIs from (malicious or erroneous) intensive usage.</p><p>Rate-limiting seems straightforward: we only allow a given client to perform X calls every minute. It’s quite easy to implements on a single server instance, and we can easily find libraries to do that for us. But our API is hosted in 6 data centers (in Europe, North America, and Asia), with multiple instances in each one. This means we need some kind of distributed rate-limiting system.</p><blockquote>Rate limiting is not only about counting calls, it’s also about communicating the current state of the limit to your client (for example using <a href="https://tools.ietf.org/id/draft-polli-ratelimit-headers-00.html">dedicated headers</a> and status codes). But this article will mostly focus on the algorithms and systems that could be used for rate limiting.</blockquote><h3>Use your load balancer</h3><p>Before trying to develop your own system, it’s important to see if existing parts of your infrastructure could provide the feature you want.</p><p>So, what’s in front of all the instances on a data center and is already responsible to inspect and route traffic toward them? The load balancer. And most load balancers provide a rate-limiting feature or some kind of abstraction that can be used to implement it. For example, HAProxy has <a href="https://www.haproxy.com/blog/introduction-to-haproxy-stick-tables/">stick tables</a> that can be used to set up rate limits. It works well, it handles synchronization between instances for you and it’s already there.</p><p>Sadly, some of our feature requirements (dynamic limits, token introspection, …) meant that we needed something more specific.</p><h3>Naive approaches</h3><h4>Sticky sessions</h4><p>Speaking of load-balancer, we don’t need a distributed rate-limiting system if a given client is not load-balanced and always interacts with a single instance 🤓. Most clients will reach the data center closer to their application (via our geo-DNS), so if we enable “stickiness” on the load balancer, a client should always reach the same instance. And this would allow us to use a simple “local” rate-limiting.</p><p>This works in theory, not in practice. The load faced by Criteo systems is not constant. For example, the Black Friday / Cyber Week is the biggest part of the year for us. During this period, our team is on alert, and we are prepared to scale our infrastructure to face the increased demand from our clients. But session stickiness and scaling don’t mix well (what’s the use of creating new instances, if all existing clients are stuck to the old ones?).</p><p>Using a smarter session stickiness, which reshuffles sessions when scaling, would help. But it means each time we scale up, clients could be switched to another instance, which has no idea how many calls the client performed on the previous instance. In essence, this would make our limit inconsistent each time we scale, allowing clients to make more calls each time our system is under pressure.</p><h4>Chatty servers</h4><p>If a client can reach any of the instances, it means that the “call count” must be shared between the instances. One way to do it would be to have each instance call every other one to ask for their current count for a given client, and sum that up. Or we could do it the other way around, with each server broadcasting a “count update” to the others.</p><p>This has two main problems:</p><ul><li>The more instances we have, the more calls need to be made.</li><li>Each instance needs to know the address of every other one, and this has to be updated each time the service is scaled up or down.</li></ul><p>While this solution can be done (it’s essentially a peer-to-peer ring and a lot of systems have been implemented to do that well), it’s far from trivial.</p><h4>Kafka streams</h4><p>If we don’t want to have each instance talking to the others, we could use Kafka to synchronize the counters in all the instances.</p><p>For example, each time a call would reach an instance, an event would be pushed to a topic. Those events would be aggregated with a sliding window (Kafka Stream does that quite well) and the up-to-date counts for each client for the last minute would be published on another topic. Each instance would then consume this topic to get the shared count of all clients.</p><p>The problem is that Kafka is, in essence, asynchronous. While the lag is often quite small, it will increase when the load on the API increase. And if the instances use outdated counters, they could allow calls that should be blocked.</p><p>All those solutions have something in common: they work well when everything is fine, but they degrade under heavy load. That’s how we design most of our system, and it’s perfectly fine usually. But rate-limiting is not a typical component, as its very goal is to protect the rest of the system from this heavy load.</p><blockquote>The goal of a rate-limiting system is to work well when the system is under heavy load. It needs to be built for the worst 1%, not the good 99%.</blockquote><h3><strong>Distributed algorithms</strong></h3><p>What we need is a centralized and synchronous storage system and an algorithm that can leverage it to compute the current rate for each client. An in-memory cache (like Memcached or Redis) is ideal. But not all rate-limiting algorithms can be implemented with every caching system. So let’s see what kind of algorithm exists.</p><p>For simplification, we will consider that we are always trying to implement a “100 calls per minute” limit.</p><p>Let’s look at the tools at our disposal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QLl1wxFlzgTKAABs" /><figcaption>Photo by <a href="https://unsplash.com/@barnimages?utm_source=medium&amp;utm_medium=referral">Barn Images</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Sliding window via event log</h4><p>If we want to know how many calls a client did in the past minute, we could store a list of timestamps in the cache for each client. Each time a call is made, the corresponding timestamp is appended to the list. Then we can loop over each item in the list, discarding the ones that are more than a minute old and counting the ones that are not.</p><p>👍<strong>Pros:</strong></p><ul><li>Very accurate</li><li>Simple</li></ul><p>👎<strong>Cons:</strong></p><ul><li>Require strong transactional support (Two instances handling calls for the same client will want to update the same list).</li><li>The size of the stored object (the list) can be quite big depending on the limit and the number of calls.</li><li>Performances are not stable (More calls mean more timestamps to go through)</li></ul><h4>Fixed window</h4><p>Most distributed caching systems have specific, high-performance, abstraction for “counters” (an integer value that can be increased atomically and that is attached to a string key).</p><p>It is very easy to maintain a counter for each client, with the key “{clientId}”. But this would simply count the number of calls the client made, <strong>since the counter creation</strong>, not over the last minute. Using the key “{clientId}_{yyyyMMddHHmm}” would allow us to maintain a counter for each client for each calendar minute (in other words: for each fixed window of 1 minute). Looking for the counter corresponding to the current time would then give us the number of calls performed by the client this minute. And if this number is above the limit we can block the call.</p><blockquote>Note that this is not the same thing as “over the last minute”. If a call is made at 07:10:23 AM, the fixed window counter will give us the number of calls made between 07:10:00 AM and 07:10:23 AM. But what we really want is the number of calls made between 07:09:23 AM and 07:10:23 AM.</blockquote><p>In a way, the fixed window algorithm “forgets” how many calls were made before the minute mark, so a client could theoretically perform 100 calls at 07:09:59 and then 100 additional calls at 07:10:00.</p><p>👍<strong>Pros:</strong></p><ul><li>Very fast (a single atomic increment+read operation)</li><li>Very basic transactional support is needed (atomic counter)</li><li>Constant performances</li><li>Simple</li></ul><p>👎<strong>Cons:</strong></p><ul><li>Inaccurate (up to x2 calls let through)</li></ul><h4>Token bucket</h4><blockquote>It’s 1994, and your parents dropped you off at the arcade to play Super Street Fighter II with your friends. They gave you a small bucket filled with $5 in coins and went to the bar across the street. Every hour, one of them comes and drops $5 worth of coin in the bucket. You’ve been essentially rate-limited to $5 an hour (and hopefully you became very good at Street Fighter).</blockquote><p>That’s the main idea behind the “token bucket” algorithm: instead of a simple counter, a “bucket” is stored in the cache for each client. A bucket is an object that consists of two attributes:</p><ul><li>the number of remaining “tokens” (or remaining calls that can be made)</li><li>the timestamp of the last call.</li></ul><p>When a call is made, the bucket is retrieved. New tokens are added to the bucket depending on the amount of time between the current call and the last call. After that, if there is more than one token, it is decremented and the call can be made.</p><p>So, contrary to my “Street fighter” example, there is no “parent” that has to refill the buckets every minute. The bucket is efficiently refilled in the same operation as the token consumption (with the number of tokens corresponding to the time gap between the last call). If the last call was half a minute ago, the 100 calls per minute limit would mean 50 tokens would be added to the bucket. If a bucket is too “old” (the last call is more than 1 minute), the token count is reset to 100.</p><p>In fact, you could choose to initialize the bucket with more than 100 tokens (but have it refill at a 100 tokens/minute rate): this would be akin to a “burst” feature, where a client could go above the limit for a short period of time, but would not be able to sustain it.</p><blockquote><strong>Note</strong>: It’s important to compute a decimal value for the tokens to be added or you risk improperly replenishing the bucket.</blockquote><p>This algorithm offers perfect accuracy while working at constant performance. The main problem is the need for transactions (you don’t want two instances updating the cached object at the same time).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iaQ44hHf8T81mrJy-Bd9ug.png" /><figcaption>Step-by-step example of a Token bucket for a valid call and a limit of 100 calls per minute</figcaption></figure><p>👍<strong>Pros:</strong></p><ul><li>Very accurate</li><li>Fast</li><li>Constant performances</li><li>Tuning the initial token number allow client to “burst”</li></ul><p>👎<strong>Cons:</strong></p><ul><li>More complex</li><li>Require strong transactional support</li></ul><blockquote><strong>Leaky bucket: </strong>another version of the algorithm (the “leaky bucket”) also exists. In this version, the calls pile up in the bucket and are handled at a constant rate (that matches the rate limit). If the bucket overflow, the incoming calls are refused. This is more complex to implement but allows to smooth the load on your services (which is something that you may want, or not).</blockquote><h4>🏆 The best?</h4><p>Looking at those three algorithms, the token bucket seems to offer the best compromise of performances and accuracy. But it’s only possible if your system offers good transactional support. That is perfect if you have access to a Redis cluster (you can even implement the algorithm as a Lua script to make it run directly on your Redis cluster, for increased performances), but Memcached only supports atomic counter, not transactions.</p><blockquote>It’s possible to implement an <a href="https://en.wikipedia.org/wiki/Optimistic_concurrency_control">optimistic concurrent</a> version of the token bucket using Memcached, but this would be more complex, and optimistic concurrency’s performance degrades under heavy load.</blockquote><h3>Approximated sliding window from fixed windows</h3><p>Without strong transactional support, are you condemned to use the inaccurate fixed window algorithm?</p><p>Kind of, but it can be improved. Remember that the main problem with the fixed window is that it “forgets” what happened just before the minute mark. But we still have access to this information (in the counter for the previous minute). So we could use it to estimate the number of calls in the previous minute by computing a weighted average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gxe-if0-1gVfoFP3OZ0B3w.png" /><figcaption>60s fixed-windows composition used to approximate a sliding 60s window</figcaption></figure><blockquote><strong>Example</strong>: If a call is made at 00:01:43 AM, we increment and get the value of the “00:01” counter. As this is the current calendar minute, it will now contain the number of calls between 00:01:00 AM and 00:01:43 AM (the last 17 seconds have not occured yet).<br>But we want the number of calls in the 60s sliding window, so we are missing the count for the 00:00:43 AM to 00:01:00 AM period. For those, we could use the “00:00” counter, and adjust it by a 17/60 factor to account for the fact that only the last 17 seconds interest us.</blockquote><p>Under constant load the approximation is perfect. But it will be overestimated when most of the calls were made at the start of the previous minute. And it will be underestimated when most of the calls were made at the end of the previous minute.</p><h4>Let’s compare</h4><p>To more accurately understand the accuracy difference, the best thing is to simulate both algorithms under the same conditions.</p><p>This first graph shows what the “fixed counter” algorithm will return with a random traffic input. The grey line is the output of a “perfect” sliding window, which at any point in time corresponds to the number of calls made in the past 60 seconds. It’s what we aim for. <strong>The orange-dotted line represents what the fixed window algorithm “counts” for the same traffic</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f32OFMmBk1IDf1keuYmJOQ.png" /></figure><p>Both output the same thing during the first minute, but soon we can see big drops for the fixed-window version at each minute mark. We can see that the fixed window algorithm will very rarely go above the 100 calls limit, meaning it would have let go quite a lot of calls that should have been stopped. Yikes!</p><p>This second graph represents the same scenario, with the same traffic, but using the approximated sliding window. Again, the grey line represents the “perfect” sliding window. <strong>The orange dotted line represents the approximated algorithm</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GK-Zy-IDJGX3TcZnZWArUg.png" /></figure><p>We no longer see drops around the minute marks and we can see that the new version of the algorithm more closely matches the perfect one. It sometimes goes a bit over, sometimes under, but overall a tremendous improvement.</p><h4>Diminishing returns</h4><p>But can we do better?</p><p>Our approximation use only the current and previous 60s fixed windows. But instead, we could use several, smaller, sub-windows. An extreme approach would be to use sixty 1s windows to reconstruct the traffic over the last minute. Obviously, this would mean reading 60 counters for each call, which would add a big performance cost. But we could choose any fixed-window duration, and compose an approximation from them. The smaller the windows, the more of them are needed and the more precise the approximation will be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulzcfZrETy0jALTFqbPCfw.png" /></figure><p>Let’s look at what combining five 15s windows would do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OONVSVj3p166pkw-9LRt3g.png" /></figure><p>As expected, the accuracy improved but is still not perfect.</p><p>We are in a classic <strong>better accuracy = worse performance</strong> scenario. In the end, there is no absolute best, you will have to look into your accuracy and performance requirement to find the solution that suits you the best. A simple fixed window could even be a very viable solution if the only thing you care about is protecting your service from gross overuse, without needing to consistently enforce a limit.</p><h3>Conclusions</h3><p>Rate-limiting is one of those features that are very simple to describe but hide a lot of complexity. Hopefully, this article helped you understand the tools and algorithms involved in making rate-limiting works in complex, distributed, systems.</p><p>Thank you for reading! Leave a comment if you have questions about rate limiting. And if you’d like to help us build even better APIs, <a href="https://careers.criteo.com/working-in-R&amp;D">we’re hiring</a>.</p><p><strong>Want to join the fun? Check out our open positions:</strong></p><p><a href="http://careers.criteo.com/">Careers at Criteo | Criteo jobs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a35f7e24783" width="1" height="1" alt=""><hr><p><a href="https://medium.com/criteo-engineering/distributed-rate-limiting-algorithms-a35f7e24783">Distributed Rate-Limiting Algorithms</a> was originally published in <a href="https://medium.com/criteo-engineering">Criteo Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance tuning for an AWS Lambda-based API]]></title>
            <link>https://medium.com/codex/performance-tuning-for-an-aws-lambda-based-api-b8b49b2d07db?source=rss-475d24faa679------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8b49b2d07db</guid>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Jean Baptiste Muscat]]></dc:creator>
            <pubDate>Sun, 21 Nov 2021 17:23:01 GMT</pubDate>
            <atom:updated>2021-11-22T21:03:42.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performance tuning for an AWS Lambda-based API (Detecting Paris’ locked bicycle stations 5/5)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sWhVQaw2n8ms7Rga" /><figcaption>Photo by <a href="https://unsplash.com/@dylu?utm_source=medium&amp;utm_medium=referral">Jacek Dylag</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>This series of articles is about me spending way too much time trying to solve a niche problem (detecting locked bicycle stations in Paris, see <a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Part 1</a>) while learning how to use the AWS Serverless stack. To find the other articles, skip to the bottom of the page.</blockquote><p>In <a href="https://medium.com/codex/creating-a-serverless-api-and-hosting-a-frontend-with-s3-b50e61a8f707">Part 4</a>, I created the frontend and the API for my <a href="http://www.velinfo.fr/">www.velinfo.fr</a> web application that computes and displays the status of the 1.500 Paris bicycle stations.</p><p>Everything is working fine, but the site is quite slow. The static content takes some time to load, and the API is not very responsive. How can I improve that?</p><h3>Frontend caching with CloudFront</h3><p>A simple solution when you want to serve static content (like the static files of a website) faster, is to use a CDN or <a href="https://en.wikipedia.org/wiki/Content_delivery_network">Content Delivery Network</a>. It’s a distributed network of servers, that will be used to cache your content (from simple files to videos) as close as possible to your users. More precisely, the CDN will be “in front” of your application, meaning that the client will call it instead of your site. And the CDN will call your site if it does not already have the content in cache.</p><p>There are a lot of independent CDNs to choose from, from Akamai to Cloudflare. But, as AWS has its own CDN (<a href="https://aws.amazon.com/cloudfront">CloudFront</a>), I’ll use this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeMugTgDQX-81GQEYw1d6A.png" /><figcaption>CloudFront locations</figcaption></figure><p>Setting up CloudFront in the CloudFormation template is simple. You need to define a “Distribution” (how and what will CloudFront cache) and define :</p><ul><li>the HTTP methods you want to cache (GET and HEAD for me)</li><li>what is the “Origin”(the source of the content that the CDN is proxying, so the website’s S3 bucket in our case)</li><li>what is the caching behavior (for how long the content should be cached, what happens in case of missing content, …)</li><li>what is the <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PriceClass.html">price class</a> to use (which correspond to how many locations will be used)</li></ul><p>And not forget to update the CNAME DNS record for “www.velinfo.fr” so that it points to the distribution instead of the S3 bucket.</p><p>All this can be done via the AWS web console, but as for the rest of my application, I will define it directly in my CloudFormation file instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf3c93c3e25fa4af306c4b843cc56dd6/href">https://medium.com/media/cf3c93c3e25fa4af306c4b843cc56dd6/href</a></iframe><h4>Performance improvements</h4><p>To assess the performance gains, I’ll use <a href="https://tools.keycdn.com/performance">KeyCDN’s performance test</a> and focus on European cities. The most important metric is the TTFB (Time To First Byte), which represents the wait time before the call is answered.</p><p>The improvement is noticeable: from ~55ms to ~25ms. Nice!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*TSsMvCQVuBxaiYgjfkf0qg.png" /></figure><blockquote><strong>Note</strong>: Now that CloudFront is set up, I no longer need to make the website S3 bucket publicly accessible. Only the CloudFront distribution should access it.</blockquote><h4>How much does it cost?</h4><p>CloudFront <a href="https://aws.amazon.com/cloudfront/pricing/">pricing </a>is based on three axes:</p><ul><li><strong>The amount of data transferred from CloudFront to the internet</strong>: $0.085/GB (it gets cheaper with more traffic)</li><li><strong>The amount of data transferred from the origin to CloudFront</strong>: $0.020/GB</li><li><strong>The number of HTTP(S) calls</strong>: $0.0120 / 10.000 HTTPS calls</li></ul><p>Currently, loading the homepage performs about 10 calls to my frontend domain, for about 300KB. The number of calls to the origin is negligible because the content will only change after a deployment so it can stay in the cache for very long.</p><p>Realistically, I’m not expecting more than a few thousand users. So let’s say 10.000 daily users, that would give me~3 GB of daily outgoing traffic and ~100.000 calls, so <strong>about $0.375 per day</strong>. And that does not account for the fact that most of this static content will be cached in the client browser anyway.</p><h3>Analyzing Lambda performance with X-Ray</h3><p>The static content of my site is loading faster, but my API is still too slow.</p><p>For example, the <em>GET /stations </em>endpoint, which returns the current state, status, and characteristics of each bicycle station takes more than 12 seconds to finish!</p><p>I already made sure that my DynamoDb calls were made in parallel, so I’m not really sure of what could be done to improve it further. Luckily, I can use AWS <a href="https://aws.amazon.com/xray/">X-Ray</a> to more finely understand where is my performance bottleneck.</p><p>X-Ray is a system that traces each call made within your application to help identify performance issues. To use it on a NodeJs Lambda function, you need to enable it for your function( in the web console for example), import the aws-xray-sdk package and use the AWSXRay.CapureAWS() method to wrap your call to your function’s dependencies (the call to DynamoDb in my case).</p><p>Then, in the X-Ray web console, you’ll be able to see the detailed traces of each call during a function execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRtDscXQiToWQmxFt37lKA.png" /><figcaption>An X-Ray trace for a GetStations function call.</figcaption></figure><p>Here I can clearly see that my three DynamoDb calls are correctly made in parallel, but that the longest one is lasting 8 seconds!</p><p>This seems very slow for a simple read operation, so is there something wrong with DynamoDb? Well, the 8 seconds do not only represent the time spent on the database side but also the time spent on the function’s side marshaling / unmarshalling the data (DynamoDb stores the objects as a typed JSON and needs to be processed before being used). And these kinds of operations are CPU intensive.</p><p>What we are really seeing is the CPU limitation of a standard Lambda function.</p><h4>Increasing a Lambda function CPU performance</h4><p>By default, a Lambda function only uses 128MB of memory and has access to a fraction of a vCPU core. It is easy to increase the memory (by setting the MemorySize parameter in the SAM/CloudFormation template, up to 10240MB), but there is no way to assign more CPU. That’s because the CPU power automatically scales with the assigned memory.</p><p>To put it simply:<strong> to have more CPU power, you need more memory</strong>.</p><p>More specifically, <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-function-common.html#configuration-memory-console">you reach a full vCPU core at the 1769MB mark</a>. Once you assign more memory, you will start having more than one thread, but single-thread performance will already be maxed out at 1769MB.</p><p>So let’s set the GetStations Lambda function to 1769MB and see what kind of performance gains we will have with a full core.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFaJrQfF4M17QhpiA21M1w.png" /><figcaption>X-Ray trace after increasing the memory to reach a full vCPU thread.</figcaption></figure><p>From 12.6s down to 811ms, not bad 😊.</p><p>What about the cost? The increase in memory impacts the cost per milliseconds proportionally. This means my 1769MB Lambda costs ~14 times more to run than a standard 128MB Lambda. but it also runs ~15 times faster. So, in my case, increasing the memory (and the performance) is cheaper!</p><p>Doing the same optimization of other endpoints offers similar performance gains. I could also increase the <em>memorySize </em>for the Lambda functions that are part of the internal detection system, but I’ve no performance constraint there as they simply run once every minute.</p><h3>The numerous ways to cache an API</h3><p>Now that each Lambda function serving an endpoint is optimized, let’s do a simple performance test. I’ll call 50 times in a row one of the heaviest endpoints (<em>GET /prediction/by-station</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*j0tm2aRExggtNWBv-Pkr7g.png" /><figcaption>Response time for successive calls to the prediction/by-station endpoint.</figcaption></figure><p>For the first ~20 calls, the endpoint behaves consistently. It takes about 3 seconds to finish. Then the response time starts to increase, with some calls failing, ending with a full failure for the last 10 calls.</p><p>So what happened? Well, we just went over the DynamoDb table read capacity, so our read operation has been throttled. Worse, while the endpoint was failing, some of the functions of the internal detection pipeline also failed, because they read from the same table and have also been throttled.</p><blockquote>You’ll find more details about the DynamoDb RCU (Read Capacity Unit) and WCU (Write Capacity Unit) in <a href="https://ouvreboite.medium.com/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699">Part 2</a>.</blockquote><p>In other words: if there are too many calls on my API, the API fails and, even worst, it may break the internal detection pipeline.</p><p>What could I do?</p><p>Increasing the Read Capacity of all the concerned tables would be the simplest solution, but this could quickly become costly as I’m already maxing out the free-tier limit. And it would only postpone the problem, simply requiring more calls before failing.</p><p>I could also create a new set of tables that would only be written to by the pipeline functions and read from by the API functions. They would serve as an isolation layer. But for those tables to sustain a high number of calls would still require more RCU than I can afford.</p><p>Instead of trying to increase the throughput of my tables, maybe I should be focusing on finding a way to cache my data so that my tables are simply less called.</p><h4>Hit rate</h4><p>One important metric to assess the usefulness and the cost of any caching solution is the hit rate. It is the ratio of the number of calls that a cache was able to answer over the total number of calls. The bigger the hit rate, the more useful the cache is.</p><p>Obviously, the hit rate depends on the design and the use case of my API. For example, an endpoint that would return data customized for the caller would result in a low hit rate, as a given response could only be cached for a single user.</p><p>Luckily my API is very simple and consists only of a handful of endpoints, with no parameter, that are user-independent and whose content is only updated every 60s or so. So I can expect a very good hit rate.</p><h4>DynamoDb Accelerator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*ReLhGg_-UbnSaZFhYN2q7A.png" /></figure><p><a href="https://aws.amazon.com/dynamodb/dax/">DynamoDb Accelerator</a> (or DAX) is a managed cache for DynamoDb.</p><p>More specifically it’s a <a href="https://aws.amazon.com/blogs/database/amazon-dynamodb-accelerator-dax-a-read-throughwrite-through-cache-for-dynamodb/">read-through/write-though</a> cache. It will greatly increase the read performance of the DynamoDb tables it is caching, and every read operation that is answered by DAX won’t consume any read capacity from the table.</p><p>Internally, it consists of a cluster of one or several cache nodes. Think of those nodes as small EC2 instances that are created in your name by AWS. As for any EC2 instance, they need to be set in a sub-network (a VPC, or Virtual Private Cloud). You pay for the size and number of those nodes. With the smallest node starting at about $30 a month.</p><p>✅Fixed cost, would benefit all functions, would improve the performance of all calls.</p><p>❌Requires updating the data layer, requires setting up a VPC, won’t reduce the number of Lambda or Gateway calls, the base cost is expensive for a pet project.</p><h4>Elasticache</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*4_a6nWDDO_QoIkkRmn049Q.png" /></figure><p><a href="https://aws.amazon.com/elasticache">Elasticache</a> is AWS-managed distributed cache. The caching technology can be Memcached or Redis, depending on your needs.</p><p>A Lamba can connect to an Elasticache cluster to fetch data, the rest of the implementation is up to me. I could simply use it as a side cache, or update the pipeline’s functions to write directly in the cache and have the API read from it instead of the DynamoDb tables.</p><p>As for DAX, Elasticache consists internally of a set of managed EC2 instances and requires the creation of a VPC. The pricing depends on the number and size of the nodes, with the smallest node costing about $10 a month. But, depending on how the cache is implemented, you may want to have at least two nodes to ensure high availability.</p><p>✅Fixed cost, the caching logic is up to you.</p><p>❌Requires rewriting part of the application to implement the caching logic, requires setting up a VPC, won’t reduce the number of Lambda or Gateway calls.</p><h4>Using a Lambda instance’s own memory</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*Tul4Kz_iRXmBXR9KtEbDoA.png" /></figure><p>When a call reaches the API Gateway, an instance of the corresponding Lambda is started to answer it.</p><p>But starting a Lambda takes some time (it’s a “cold start”). So, to minimize this, Lambda keeps the instances alive for a few minutes after a call is finished, in case the same function would be called again.</p><p>We can take advantage of that by caching some data directly in a Lambda’s instance (by assigning a variable outside the event handler function for example). The next time this Lambda is called, if the same instance is reused, the data will still be there.</p><p>This solution has two major limitations:</p><ul><li><strong>predictability</strong>: we have no control over when an instance is freed or kept, so the hit rate of this caching solution can’t be predicted</li><li><strong>concurrency</strong>: when a Lambda function needs to be started, if a corresponding instance exists but is currently in use (answering a concurrent call for example), Lambda has no choice but to create a new instance. This means that the “hit rate” will be worse in high load situations as more and more fresh instances will be created…</li></ul><p>✅Free!</p><p>❌Only a marginal improvement, won’t provide any guarantee under load, won’t reduce the number of Lambda or Gateway calls.</p><h4>API Gateway’s cache</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*MV1-pNOAnyMmEPaheT5ltA.png" /></figure><p>The <a href="https://aws.amazon.com/api-gateway/">API Gateway</a> offers a caching functionality, that can cache the data it returns.</p><p>In contrary to DAX or Elasticache, no VPC needs to be set up as the cache nodes are “owned” by the Gateway. In fact, you don’t have to select a number or type of nodes, but only the total memory you need for the cache, everything is handled by the Gateway.</p><p>The setup is fairly simple: you just need to choose a memory size, a retention period and flag the endpoints you want to be included in the cache.</p><blockquote>The ApiGateway comes in two flavors: the RestAPI and the HttpApi. The RestApi provide more features. The HttpApi is more performant and cheaper by about x3. Only the RestApi support caching.</blockquote><p>The pricing is based on this memory size, with a minimum of 0.5GB for about $15 a month.</p><p>Compared to the previous solution, this one offers an additional advantage: as the cache is “earlier”, each time it can answer a call, no Lambda function will have to be called.</p><p>✅Fixed cost, reduce the number of Lambda calls, simple to set up</p><p>❌Requires using the RestApi flavor which is more costly than the HttpApi, moderate fixed cost</p><h4>CloudFront</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*O_5RoMwaMwcpprEPu6QZMg.png" /></figure><p>As for the static website content, a CDN (CloudFront here) could also be used to cache the data. In fact, from CloudFront’s perspective, caching an API or a website is mostly the same.</p><p>Using CloudFront would have additional benefits:</p><ul><li>The data is cached closer to the user (even if that is not very useful for a service that only concerns a single city)</li><li>Cloudfront can handle some other features, like content-compression</li></ul><p>Setting up the distribution is similar to what I’ve just done for the website static contents, with a few exceptions:</p><ul><li>The TTL will be shorter (60 seconds)</li><li>I need to forward the header needed for CORS</li></ul><p>Instead of using the in-line parameters, I will define a proper CachePolicy this time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b93d64b4691b3beb6e2fb06486bf9d0/href">https://medium.com/media/4b93d64b4691b3beb6e2fb06486bf9d0/href</a></iframe><p>The <a href="https://aws.amazon.com/cloudfront/pricing/">pricing</a> is more complex as it depends on the number and size of calls. But, this is where things get interesting: <strong>a call answered by CloudFront is cheaper than a call answered by the ApiGateway</strong>:</p><ul><li><strong>Call cost</strong>: HttpApi $0.035 per 10.000, CloudFront $0.012 per 10.000</li><li><strong>Data transfer cost</strong>: HttpApi $0.09 per GB, CloudFront $0.085/GB</li></ul><p>Obviously, this is true only because my hit rate will be high and because CloudFront won’t have to call the underlying API Gateway very often (which would add cost).</p><p>✅Cost savings, cost scale with usage</p><p>❌Setup is tedious, cost scale with usage</p><h4>And the winner is…</h4><p>From a cost perspective alone, CloudFront is the clear winner. The setup won’t require any rewriting of my functions, which will make the setup simple.</p><p>If my API had been more complex (which would have generated a lower hit rate), I would have maybe used DAX, as it would have offered the most robust, yet simple, solution.</p><p><strong>Winner: 👑CloudFront👑</strong></p><p>So, how well does it work?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*3kFP-ai8WPvlpjHoQt0mDw.png" /><figcaption>Careful, the scale is logarithmic</figcaption></figure><p>As before, the first call takes about 3 seconds to finish. But all the following calls last only ~10ms. I think we can say this is successful 😊</p><h3>Conclusion</h3><p>Even if AWS wants you to think that Lambda will allow you to <em>run code without thinking about servers or clusters</em>®, it obviously becomes more complicated as soon as you have to improve performance.</p><p>But I see that as a good thing: it means that even within the walls of the serverless stack, I’m not constrained to a single solution for when I’m facing a problem. I can leverage several tools and even rely on “non-serverless” tools like Elasticache.</p><p>This has been true for the specific subject of this article (performance) and for the others in this series.</p><p>It’s been more than a year since I started working on this project. It’s still a little bit wonky, the frontend design is basic but I achieved what I really wanted to do: understand what this “serverless” stuff was about, get more comfortable with AWS, and build a “real” application.</p><p>I hope you had as much fun reading me as I add working on this! If you want to look at some messy code, you can find the sources on Github: <a href="https://github.com/ouvreboite/velinfo">https://github.com/ouvreboite/velinfo</a></p><p>Saving costs was a primary objective, which will allow me to maintain the application online without thinking much about money. I’m also happy to report that the team at Velib seems committed to improving their service. Hopefully, my application will soon become obsolete!</p><p>As for me, I opted for a more radical solution: I bought my own bike.🚴</p><ul><li><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Part 1</a>: Choosing the AWS serverless stack for a prototype</li><li><a href="https://ouvreboite.medium.com/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699">Part 2</a>: The backbone of a serverless app: Lambda functions and DynamoDb tables</li><li><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-3-d532318dfca7">Part 3</a>: Implementing a real-time detection algorithm with Lambda functions and DynamoDb streams</li><li><a href="https://ouvreboite.medium.com/creating-a-serverless-api-and-hosting-a-frontend-with-s3-b50e61a8f707">Part 4</a>: Creating a serverless API and hosting a frontend with S3</li><li><a href="https://medium.com/codex/performance-tuning-for-an-aws-lambda-based-api-b8b49b2d07db">Part 5</a>: Performance tuning for a Lambda-based API</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8b49b2d07db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/performance-tuning-for-an-aws-lambda-based-api-b8b49b2d07db">Performance tuning for an AWS Lambda-based API</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a serverless API and hosting a frontend with S3]]></title>
            <link>https://medium.com/codex/creating-a-serverless-api-and-hosting-a-frontend-with-s3-b50e61a8f707?source=rss-475d24faa679------2</link>
            <guid isPermaLink="false">https://medium.com/p/b50e61a8f707</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jean Baptiste Muscat]]></dc:creator>
            <pubDate>Sun, 14 Nov 2021 21:07:23 GMT</pubDate>
            <atom:updated>2021-11-22T21:01:53.230Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a serverless API and hosting a frontend with S3 (Detecting Paris’ locked bicycle stations 4/5)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gSePhCLa-2aWB7jn" /><figcaption>Photo by <a href="https://unsplash.com/@alessandracaretto?utm_source=medium&amp;utm_medium=referral">Alessandra Caretto</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>This series of articles is about me spending way too much time trying to solve a niche problem (detecting locked bicycle stations in Paris, see <a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Part 1</a>) while learning how to use the AWS Serverless stack. To find the other articles, skip to the bottom of the page.</blockquote><h3>UX and API Design</h3><p>After having implemented a detection algorithm using DynamoDb Streams and Lambda functions (see <a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-3-d532318dfca7">part 3</a>), I need a frontend to display the results. A simple HTML table listing the status of each station will be enough, but where is the fun in that? So I’ll create a basic but functional app giving the ability to anyone to find the closest station and see its current content and state. I will also use this application to display some of the statistics my pipeline is computing.</p><p>But before spending hours on development, I’ll first work on a simple mockup. And for each page, I’ll try to define which API will be required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUpxIHlDzFHNM5lPOn4-HQ.png" /><figcaption>A simple mockup of the web app, with the corresponding API endpoints being called.</figcaption></figure><p>In the end, I settled on five main pages:</p><ul><li><strong>The home page</strong> contains a few metrics about today’s network usage (with a link to a more detailed statistics page) and a list of the last stations’ change of state (the stations that went from ‘OK’ to ‘Locked’, and vice-versa).</li><li><strong>The statistics page</strong> displays today’s metrics and a chart comparing the predicted activity with the real one. I’ll use it myself to quickly monitor how good my predictions are.</li><li><strong>The map page</strong> locates the user and the nearby stations and displays them on a map, with custom pins to quickly see locked or unavailable stations. Clicking on a pin will redirect to the station’s details page.</li><li><strong>The stations&#39; list page</strong> allows a user to find a specific station by name, with a search box.</li><li><strong>The station details page</strong> represents all the information about a specific station, with a small map, details about the station’s content, and a chart displaying the station’s own activity for today.</li></ul><p>All the data required to populate those pages can be summarized by the following endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*nQedmY6HyaoH2LkoOAbSbA.png" /><figcaption>List of the API endpoints needed for the web app.</figcaption></figure><blockquote><strong>Note</strong>: ideally, I would have relied on path parameter to more easily get the activity or prediction of a single station (for example : GET /activity/{station-code}. But, cost and technical constraints regarding caching prevented me from doing that. More about that in part 5.</blockquote><h3>Serverless API with API Gateway</h3><p>Let’s start by implementing the API. Surely, to expose an API on the web you need some kind of always available server, right?</p><p>Well, no. Or more exactly, AWS provides a solution that manages that for you, and you just need to focus on what happens when an endpoint is actually called. It’s the <a href="https://aws.amazon.com/api-gateway/?nc1=h_ls">API Gateway</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AogT8Vqkb-8Gy6mb.png" /><figcaption>Shamelessly stolen from the AWS documentation</figcaption></figure><p>In a nutshell, API Gateway acts as a proxy between the web and your code. It exposes endpoints and when an endpoint is called, it triggers the service of your choice, forwarding the call’s parameters and returning whatever the service decides. In our case, we simply have to trigger a Lambda function. And from a Lambda function’s perspective, it’s just another event, with a specific <a href="https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html">event payload</a>.</p><p>So let’s create the first “<em>GET /stations</em>” endpoint:</p><p>In the SAM/CloudFormation template, we need to create a new function, and declare an “HttpAPI” event, with the wanted path and method, and a reference to the API Gateway. Then we have to create the API Gateway. SAM provides a simpler declaration with the <strong>AWS::Serverless::HttpApi </strong>type, which mostly needs the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a> configuration if needed and a reference to the domain name and related parameters. Here I’m using my own <a href="http://www.velinfo.fr/">velinfo.fr</a> (Velinfo, Velib’+info, got it?) domain name. More exactly I created a specific api.velinfo.fr subdomain just for the API.</p><p>This requires setting up a domain name through AWS <a href="https://aws.amazon.com/route53/">Route 53</a> and creating the corresponding hosted zones and certificates, but I won’t dive into this topic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e84fbdd73d57686b0f298ee66f0f5e81/href">https://medium.com/media/e84fbdd73d57686b0f298ee66f0f5e81/href</a></iframe><blockquote><strong>Note</strong>: in fact there are two SAM types for API Gateway: <strong>AWS::Serverless::Api </strong>and <strong>AWS::Serverless::HttpApi. </strong>They represents respectively the <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-rest-api.html">RestApi</a> and <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html">HttpApi</a> Gateways. The first one is the most feature rich, with its own caching for example, while the second one is the most barebone but also the most performant and the cheapest (by about x3). I’m using the last one.</blockquote><p>The Lambda function is quite similar to the ones we’ve already seen. The main differences are that it takes a specific event type as an argument and that it will return a structured object that will contain the status code, body, and potential headers needed that represent the REST response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5903ef836f11d7e0781edbb869372ccc/href">https://medium.com/media/5903ef836f11d7e0781edbb869372ccc/href</a></iframe><p>Here, I’m not using the event argument, but I could use it to find the contextual information regarding this specific API call, the path and query parameters used, and so on.</p><p>Here is what the <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/aws-lambda/trigger/api-gateway-proxy.d.ts">event </a>would look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7fa46c808f2d7e088dd39eb20b7b503/href">https://medium.com/media/d7fa46c808f2d7e088dd39eb20b7b503/href</a></iframe><p>Let’s deploy the new endpoint (using sam deploy as usual) and test it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGXhb1JWNYWu4ruzb1o7FA.png" /><figcaption>Endpoint call using Postman.</figcaption></figure><p>Works well!</p><p>Most of my endpoints are simply exposing what’s inside a specific DynamoDb table, so I’ll skip their implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7e3_wt-Z62u_g_vBHFS9fw.png" /><figcaption>API Gateway endpoints and associated Lambda functions and DynamoDb tables.</figcaption></figure><h3>Frontend hosting with S3</h3><p>With the API created, I can start implementing the frontend. As Angular development is not the topic of this article, I’ll fast forward a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*zd21rK1h25qo1ewHvdHB6w.png" /><figcaption>A station’s details page. Only in French at the moment.</figcaption></figure><p>For those interested, I mostly relied on the <a href="https://material.angular.io/">Angular Material</a> component library for basic styling and structure. I used <a href="https://www.npmjs.com/package/@agm/core">agm</a> for the map (maybe not the most logical choice in the long run, as Google Maps’ free plan is quite restrictive) and <a href="http://twitter.com/swimlane/ngx-charts">ngx-charts</a> for the custom charts.</p><p>I can build my frontend app, and generate the corresponding static files using the Angular CLI: ng build --prod</p><p>But, how am I supposed to host that? Obviously, I could rent a server at any web hosting company and host my application there, but that would not be very “serverless” 😉</p><p>In Part 1, I quickly talked about <a href="https://aws.amazon.com/s3">S3</a>, AWS’s “Simple Storage Service”.</p><p>S3 is an extremely resilient object storage service. An object can be anything, a .html or a .css file for example. And what is a frontend application, if not a bunch of static files served to a web browser?</p><p>Even if web hosting was not initially a core functionality of S3 (it was really intended as a storage service, where objects/files would be manipulated through an SDK or an API), hosting static websites quickly became an obvious use case for S3 and a <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/HostingWebsiteOnS3Setup.html">web hosting feature</a> was introduced.</p><p>To use it, we first need to define a new S3 “bucket” (a bucket is a unit of storage in S3, see it as a shared folder) and define a WebSiteConfiguration to specify where is the index document (in my case, the index.html file at the root of the bucket). We also need to define an access policy allowing everyone to read the content of the bucket. Finally, we need to know what is the public URL that has been generated for this bucket so I’ll add an Output for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef5fd54e2b9bcede3f9abe290800f070/href">https://medium.com/media/ef5fd54e2b9bcede3f9abe290800f070/href</a></iframe><p>To create the bucket, I simply need to deploy the configuration with SAM: sam deploy . At the end of the operation, I’ll get the generated bucket’s URL.</p><p>But if I try to call that now, it returns nothing. That’s normal, as I created the bucket, but I’ve put nothing in it. I need to push my static site content to the bucket, using the AWS CLI. I’ll use the AWS CLI for that.</p><pre>#build using angular CLI<br>ng build --prod</pre><pre>#clear the bucket content<br>aws s3 rm s3://velinfo-frontend --recursive</pre><pre>#push the new content<br>aws s3 cp dist/velinfo s3://velinfo-frontend --recursive --cache-control max-age=31536000</pre><p>Calling the bucket’s URL in the browser will display the website, but the API calls fail. That’s because of our good friend <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a>, which is blocking my API call as my site (or bucket)’s domain is not <a href="https://www.velinfo.fr/">https://www.velinfo.fr</a> so it’s not in the accepted domains list.</p><p>To properly host the site on <a href="http://www.velinfo.fr,/">www.velinfo.fr,</a> I need to create a DNS record to point to the bucket’s URL. To do that, I can simply use AWS&#39;s own DNS service (<a href="https://aws.amazon.com/route53/">Route53</a>) and add a CNAME record.</p><p>Now, it’s working!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*BCD9ImGVAUV8rtXBhjHsoQ.png" /><figcaption>The website hosted on <a href="https://velinfo.fr/">https://www.velinfo.fr</a></figcaption></figure><h3>Architecture summary</h3><p>So, let’s recap what happens when I’m accessing my website:</p><ul><li>the <a href="http://www.velinfo.fr/"><strong>www.velinfo.fr</strong></a> domain name points to the <strong>velinfo-frontend</strong> S3 bucket, using a DNS record managed by Route53</li><li>the <strong>velinfo-frontend</strong> bucket is configured to serve its content as a website</li><li>the frontend application is built using the Angular CLI and is pushed to the bucket using the AWS CLI</li><li>the frontend application fetches data from the <strong>api.velinfo.fr</strong> REST API</li><li><strong>api.velinfo.fr</strong> points to the API Gateway using a DNS record managed in Route 53</li><li>the API Gateway triggers the Lambda function corresponding to the endpoint called and gives it all the information about the call</li><li>the Lambda function calls the corresponding DynamoDb table</li><li>the Lambda function returns a specific output representing the status code, headers, and body. And all this gets forwarded back by the API Gateway to the caller.</li><li>the whole infrastructure is defined in a SAM/CloudFormation template</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSm0RQVsboIQ42ILHaZXCg.png" /></figure><p>The API and the web app are now finished. But before closing the series, I want to tackle one last thing: performance.</p><p>See you in part 5!</p><ul><li><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Part 1</a>: Choosing the AWS serverless stack for a prototype</li><li><a href="https://ouvreboite.medium.com/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699">Part 2</a>: The backbone of a serverless app: Lambda functions and DynamoDb tables</li><li><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-3-d532318dfca7">Part 3</a>: Implementing a real-time detection algorithm with Lambda functions and DynamoDb streams</li><li><a href="https://ouvreboite.medium.com/creating-a-serverless-api-and-hosting-a-frontend-with-s3-b50e61a8f707">Part 4</a>: Creating a serverless API and hosting a frontend with S3</li><li><a href="https://medium.com/codex/performance-tuning-for-an-aws-lambda-based-api-b8b49b2d07db">Part 5</a>: Performance tuning for a Lambda-based API</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b50e61a8f707" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/creating-a-serverless-api-and-hosting-a-frontend-with-s3-b50e61a8f707">Creating a serverless API and hosting a frontend with S3</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a real-time detection algorithm with Lambda functions and DynamoDb streams]]></title>
            <link>https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-3-d532318dfca7?source=rss-475d24faa679------2</link>
            <guid isPermaLink="false">https://medium.com/p/d532318dfca7</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[event-based-architecture]]></category>
            <category><![CDATA[velib]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Jean Baptiste Muscat]]></dc:creator>
            <pubDate>Mon, 20 Sep 2021 20:04:25 GMT</pubDate>
            <atom:updated>2021-11-22T21:02:51.745Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing a real-time detection algorithm with Lambda functions and DynamoDb streams (Detecting Paris’ locked bicycle stations 3/5)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g2Uohu46l9awzTl7" /><figcaption>Photo by <a href="https://unsplash.com/@andrew_gook?utm_source=medium&amp;utm_medium=referral">Andrew Gook</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>This series of articles is about me spending way too much time trying to solve a niche problem (detecting locked bicycle stations in Paris, see <a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Part 1</a>) while learning how to use the AWS Serverless stack. To find the other articles, skip to the bottom of the page.</blockquote><h3>Detecting locked stations</h3><p>In <a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699">Part 2</a>, I created several Lambda functions and DynamoDb tables to fetch and store the content of each Velib station, each minute. I also computed the last time a station was active (i.e. a bike had been rented or returned from this station). With this data, I will try to detect locked stations.</p><p>A very simple algorithm would be to consider any station that has not been active for a given amount of time as locked. <em>Station A has not seen any traffic for 3 hours, so it must be locked</em>, right?</p><p>This begs the question: is the activity of the stations evenly distributed throughout the day, and are all stations equal?</p><p>Nope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPpgOSnTD2jv65XWrAxEzQ.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Box_plot">Box plot</a> of the station’s activity per hour on a typical working day. For example, at 7 PM one of the stations reached 34 bikes rented or returned while the median for the 1.500 stations was only 2.5.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhPg1L5atyUJvZ8HyYv3sg.png" /><figcaption>Most of the stations see between 20 and 40 bikes rented during a single day. But a few can reach 200 and above.</figcaption></figure><p>This was kind of expected: the traffic is totally different at 4 AM or at 4 PM. Even worse, on a single day, some stations can have a traffic of almost 400, while about 60 stations see less than 20 bikes rented or returned (and a handful of them have a daily average traffic close to 0).</p><p>With this level of disparity, a simple hard-coded threshold would not be effective. It would either be creating false positives if too low or not detect locked stations if too high.</p><h3>In search of a better metric</h3><p>If a unique time threshold is not effective, maybe I could try to compute a custom time threshold for each station, based on its past activity. But this seems complicated.</p><p>Let’s take a step back. Instead of focusing on the time since the last activity, why not focus on the number of bikes that should have been rented or returned during this time period? Put another way: <em>station A is inactive for X minutes, and usually, 20 bikes should have been rented or returned during this time, so it may be locked</em>.</p><p>We can still have a very basic threshold (20 bikes). But this threshold will be reached more quickly for the more “active” stations and will take more time for the less active ones. The disparity of activity amongst the station is built in this metric.</p><h3>Computing the missing activity</h3><p>It’s 2:34 PM and a station seems inactive since 1:07 PM. How can I know what level of activity should have occurred in those 87 minutes?</p><ul><li><strong>#1 Looking at yesterday’s data</strong>: I could load the content of the station for the same time frame yesterday and count the number of bikes rented or returned. But we are Monday, and yesterday was Sunday, so is Sunday&#39;s traffic really representative? And what if the station was already having trouble at the same time yesterday? That would return no traffic. Using a single day as a reference is not safe.</li><li><strong>#2 Using the average rate:</strong> I could easily compute an average rate (number of bikes seen / minute) for each station, and just multiply that by 87 minutes. But, as we have seen earlier, the traffic varies quite a lot during the day (and the week) so this method is not accurate.</li><li><strong>#3 Using the average rate on the same weekday and timeslot</strong>: Instead of loading yesterday’s content, I could look at the average traffic for the same weekday on the same time frame. This seems good, but the traffic at a given station can evolve with time. Maybe it’s more used in the summer, maybe a new mall opened right next to it. An average rate will take a lot of time to adjust.</li><li><strong>#4 Using the rolling median rate on the same weekday and timeslot</strong>: Instead of using an average, I can use the median over the last four weeks. That way my expected traffic will quickly adjust to a new usage pattern on a station. This will also discard the more “exceptional” days and correctly represent the “true” expected traffic.</li></ul><h3>Optimization</h3><p>Let’s go with solution #4.</p><p>I ingest the stations’ content each minute so I’ll perform a “locked station detection” every minute for each station that seems inactive.</p><p>It’s 2:34 PM and a station seems inactive since 1:07 PM. I need to find the median traffic occurring in this 87 minutes window. That means I’ll need to fetch ~87 minutes * 4 weeks = 348 items from my StationsContent table. That’s a lot! Worse, the longer a station stays inactive, the more items I need to fetch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pG-P0r5KJLaDzj0U0B-N3Q.png" /></figure><blockquote>If you recall from the <a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699">previous part</a>, I can only use 25 RCU for this whole application. With a 60 second accumulation period for the burst and a 230KB item size, it means I can realistically fetch: 25 RCU * 60s * 4KB / 230 KB =26 items each minute. And that’s if I use all my RCUs for this single table.</blockquote><p>How can I avoid doing this many read operations?</p><h4><strong>Compounding</strong></h4><p>Instead of recomputing the whole “window” each time, I could compute the missing activity on the past tick (minute) and compound it. In short, for each station that has no activity on a given tick, I can compute the missing activity just for this minute and add that to a “missing activity” state in another table. So, at a given moment, I’m only interested in knowing the median traffic for a single minute, not for a window of possibly several hours, and that means only fetching 4 items. The problem is I would need to keep a month of minute-by-minute history in the StationsContent table and that would eat a big chunk of my free 25GB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VwXAXe7McBvxm7nVYKd3vA.png" /></figure><h4><strong>Precomputing</strong></h4><p>But do I really need a minute-per-minute accuracy for the expected traffic? I could summarize the traffic of each station in 10-minutes fixed windows using a kind of Statistics table. That will give me enough accuracy and divide by 10 the amount of data I’ll need to store long-term (even more, as I could only store the activity on this timeslot, and not the other attribute that I have in StationsContent).</p><p>I can also precompute the median on this timeslot. This could prove useful later if I want to display the expected activity of a given station: I’ll simply need to look into the MedianActivity table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tggu-SevuVlQFaIGspWsQ.png" /></figure><p>This seems more complicated, but it’s the kind of tradeoff I need to make if I want to keep the cost down. I’m constrained by the free tier limitations (read/write operation and table size), but I can create how many tables I want, so I’m taking advantage of that to store the intermediary computation in dedicated tables instead of doing more expansive calls over larger data.</p><p>Note that the StationsState table contains the <em>current </em>state for each station. To follow more easily the change of state of stations during the day, I’ll create another table (StationStateChanges) which in will I’ll insert an item each time a station state changes.</p><h3>Implementation using DynamoDb stream and EventBridge</h3><p>The implementation will require three new tables (StationStatistics, MedianActivity and StationState) and three new function (ComputeStatistics, ComputeMedianActivity and ComputeState).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbG6wB1X5zUKnb3ttRiAzA.png" /></figure><p>I want to run ComputeStatistics and ComputeStationsState each time a new item is added in the StationsContent table. So I will rely on <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html">DynamoDb Steams</a>. This allows to trigger a lambda function each time an item is added/updated/removed from a Dynamo table.</p><p>To set it up using CloudFormation/SAM, I can no longer use the <em>AWS::Serverless::SimpleTable</em> type from SAM. I need to switch to the more complex <em>AWS::DynamoDB::Table</em> that exposes a StreamSpecification attribute. Then, I have to declare a <em>DynamoDB</em> event on my function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b0cc2116a696207438a9076ed62006/href">https://medium.com/media/31b0cc2116a696207438a9076ed62006/href</a></iframe><p>The Lambda function will receive the event as a parameter when it is triggered, and I can access the object that has just been inserted in the StationsContent table. After that, I’ll just need to get the statistics corresponding to the timeslot, update them with the new event’s content, and store them back.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff485ff3eecad992f344db9deabec686/href">https://medium.com/media/ff485ff3eecad992f344db9deabec686/href</a></iframe><p>The median is updated independently, every 10 minutes. So I can use an EventBridge rule (like in part 2) for that.</p><h4>Automatic retries</h4><p>By default, if your Lambda function fails when processing a DynamoDB Stream event, this event will be retried again and again. That’s perfect if your problem is transient as the retry is likely to succeed after a few times.</p><p>But if your problem is permanent (let’s say you pushed a new buggy version of your function), then the retries will happen again and again. Worse, the failed event will pile up. In my case, with one event every minute, if I take one hour to fix a fresh bug, it will mean about 60 events will be waiting to be retried. And that can cause havoc on my finely-tuned DynamoDB tables, with their carefully chosen RCUs and WCUs.</p><p>Luckily, I have two parameters at my disposal on the <em>AWS::Serverless::Function</em> resource: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html#cfn-lambda-eventsourcemapping-maximumrecordageinseconds">MaximumRecordAgeInSeconds</a> and <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html#cfn-lambda-eventsourcemapping-maximumretryattempts">MaximumRetryAttempts</a>.</p><h4>Monitoring</h4><p>I’m starting to have a few functions that run all day long. At the moment, the only way to find if they are working is by looking at the logs and each Lambda metric in the web console. It would be better if I could be notified (by mail, for example) whenever a function fails.</p><p>To do that, I can set up a few CloudWatch alarms. For example, here is an alarm that will ring when the FetchStationsContent fails at least twice in the past 5 minutes (the Velib API can be a little flaky, so I’m allowing it to fail occasionally).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*Nzc_NqAtBUvaDQFKSpq85A.png" /></figure><p>Of course, instead of setting it up in the console, I could also define the alarm in the CloudFormation/SAM template.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06cd07fc3fb6d4418d48615014ed22d1/href">https://medium.com/media/06cd07fc3fb6d4418d48615014ed22d1/href</a></iframe><p><strong>Note:</strong> you need an SNS topic to send your alarm result. I find it quicker to create it via the web console. So I’ll provide it as a parameter in my CloudFormation/SAM template.</p><h3>Bad weather and holidays</h3><p>After a few weeks, the application was behaving well. I could see my Statistics and Median table filling up, and I could look at the StationStateChanges to see the stations being detected as locked and their state changing as soon as the activity was restarting.</p><p>Then, it rained. A lot. And I saw almost a fifth of the stations being detected as locked in a single afternoon. I went to the station nearest to my flat, which had not seen any traffic for the past 3 hours and had been marked as locked. I was soaked but I was able to rent a bike without any problem.</p><p>So what happened? You already understood: nobody wants to rent a bike in the pouring rain. But my application is not able to differentiate between a “legitimate” slow down in activity or an individual station problem.</p><p>A week later, we had a public holiday in France. And something similar occurred in the morning: a bunch of stations saw very little traffic between 7 AM and 9 AM, while it was usually their busiest time slot.</p><p>Thinking about it, I was also worried about the impact of the bi-annual daylight saving time change.</p><p><em>How can I account for the weather, the public holidays, and the daylight saving time change?</em></p><ul><li>I could use a weather API (for example <a href="https://openweathermap.org/current">https://openweathermap.org/current</a>) and change my threshold when it’s raining or when there is a lot of wind or it’s very cold.</li><li>I could find some kind of API for the french public holidays (for example <a href="https://www.abstractapi.com/holidays-api">https://www.abstractapi.com/holidays-api</a>) and use “Sunday’s” median activity for those days.</li><li>I could hardcode the daylight saving time changes for the next 10 years and maybe apply a coefficient the days after a change.</li></ul><p>This seems tedious. Each new kind of problem asks for a specific data source and a specific modification to my algorithm. I don’t like it. I would prefer a single, global, solution.</p><p>What do all those problems have in common? The overall network is impacted, with the traffic being lower or higher than usual. So, why not use the overall traffic change as an input?</p><p>I can compute a “network activity ratio” that is the network’s global activity divided by the expected median traffic at a given time. And use this global ratio in my algorithm.</p><p>So my formula will go from that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*ZktzGBdAuzqCYZUNQWUHGg.png" /></figure><p>To that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*iT82nsvGuPAkOkZ_v8NMfQ.png" /></figure><p>With this updated algorithm my detection is more robust. Detecting false positives or negatives is beyond my reach (I don’t have the time to test each of the 1.500 stations every hour). But I’m quite happy with my results.</p><p>The core of the application is now finished, but I’m missing a frontend to display the status of each station.</p><p>See you in part 4!</p><ul><li><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Part 1</a>: Choosing the AWS serverless stack for a prototype</li><li><a href="https://ouvreboite.medium.com/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699">Part 2</a>: The backbone of a serverless app: Lambda functions and DynamoDb tables</li><li><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-3-d532318dfca7">Part 3</a>: Implementing a real-time detection algorithm with Lambda functions and DynamoDb streams</li><li><a href="https://ouvreboite.medium.com/creating-a-serverless-api-and-hosting-a-frontend-with-s3-b50e61a8f707">Part 4</a>: Creating a serverless API and hosting a frontend with S3</li><li><a href="https://medium.com/codex/performance-tuning-for-an-aws-lambda-based-api-b8b49b2d07db">Part 5</a>: Performance tuning for a Lambda-based API</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d532318dfca7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-3-d532318dfca7">Implementing a real-time detection algorithm with Lambda functions and DynamoDb streams</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The backbone of a serverless app: Lambda functions and DynamoDb tables]]></title>
            <link>https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699?source=rss-475d24faa679------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1967d639699</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[velib]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jean Baptiste Muscat]]></dc:creator>
            <pubDate>Mon, 02 Aug 2021 12:36:08 GMT</pubDate>
            <atom:updated>2021-11-22T21:03:08.200Z</atom:updated>
            <content:encoded><![CDATA[<h3>The backbone of a serverless app: Lambda functions and DynamoDb tables (Detecting Paris’ locked bicycle stations 2/5)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uW5nj8uss2tBnUcC" /><figcaption>Photo by <a href="https://unsplash.com/@nicoli_?utm_source=medium&amp;utm_medium=referral">Chepe Nicoli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>This series of articles is about me spending way too much time trying to solve a niche problem (detecting locked bicycle stations in Paris, see <a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Part 1</a>) while learning how to use the AWS Serverless stack. To find the other articles, skip to the bottom of the page.</blockquote><h3>Fetching the Velib’ data</h3><p>In <a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Part 1</a>, To be able to detect the locked Velib stations, the first step is to ingest the Velib API data. As we have seen previously, this <a href="https://www.velib-metropole.fr/donnees-open-data-gbfs-du-service-velib-metropole">API </a>exposes two main endpoints :</p><ul><li><a href="https://velib-metropole-opendata.smoove.pro/opendata/Velib_Metropole/station_status.json"><strong>/station_status.json</strong></a> which returns, in “real-time” (refreshed every minute) the content and status of each station.</li><li><a href="https://velib-metropole-opendata.smoove.pro/opendata/Velib_Metropole/station_information.json"><strong>/station_information.json</strong></a> which returns the characteristics of each station (geo-coordinates and name).</li></ul><p>To accurately get the evolution of each station content, I need to call the first endpoint every minute. The other one can be called less often as the characteristics rarely change. To do so, I’ll create two Lambda functions: <em>FetchStationsContent </em>and <em>FetchStationsCharacteristics</em>. The corresponding data will be stored in DynamoDb tables. To “trigger” my functions every minute (or hour), I will use EventBridge rules.</p><p>Here is what it would look like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXXgyTOAoVRvycjmcr8erQ.png" /><figcaption>Data ingestion pipeline</figcaption></figure><h3>First function</h3><p>Lambda functions can be written in virtually any language. For some (like JavaScript or Python), you can even code your function straight into the AWS web console. That’s fine for a quick prototype, but not really recommended for bigger projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmDf_mSgC2pQx91oTxlbag.png" /><figcaption>The web editor for a Javascript function</figcaption></figure><p>Most of the code for the first Kafka prototype was written in Java. But, I will use Angular for the frontend and I want to use a single language if possible, so I will write my functions in Typescript. TypeScript is not officially supported by AWS Lambda, but JavaScript is (you can choose a NodeJS backend for your function), so I will simply need to transpile my TypeScript code into JavaScript and upload it to my Lambda.</p><p>Let’s start working on the first function (fetching the stations’ content). I’ll first define some types representing the domain objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b77aac3dbfe9677d1d46a80c66a686f/href">https://medium.com/media/5b77aac3dbfe9677d1d46a80c66a686f/href</a></iframe><p>Then I will create a basic REST client using <a href="https://www.npmjs.com/package/axios">Axios</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c701ba802e7b18bd09e9d239810ee8c/href">https://medium.com/media/6c701ba802e7b18bd09e9d239810ee8c/href</a></iframe><p>The Lambda function itself simply uses the client and logs the content. I will save it in the database later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a72b8b0e8e073a18d1226bdccb873bce/href">https://medium.com/media/a72b8b0e8e073a18d1226bdccb873bce/href</a></iframe><p>The function <em>lambdaHandler </em>is what<em> </em>will be called by the Lambda infrastructure. After that, it’s a simple matter of transpiling this into JavaScript, zipping the resulting folder, creating the function, and uploading the code to it using the AWS web console.</p><p>From there I can manually run the function to make sure everything is ok. The log of each run will be visible in CloudWatch (the AWS logging and alerting service). I can see that I successfully fetched 1410 stations’ content. Perfect!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXJiqtzI9UcFHr-ewxM4Nw.png" /><figcaption>Function logs in CloudWatch</figcaption></figure><p>To run the function every minute, I need to go back to my function’s page and follow the procedure to add a trigger. I will then choose to create an EventBridge rule and specify a schedule expression. CRON expression can be used, as well as simpler “rate” expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*EfzVgWDdIwPu43OH8urA9A.png" /><figcaption>A simple EventBridge expression for “once every minute”.</figcaption></figure><p>If I go back to my function’s page, I can see that the EventBridge trigger has been attached to it. The function will now run every minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtOGGpHmGu2_7-xgu9Ru6Q.png" /><figcaption>My Lambda details page on the AWS web console</figcaption></figure><p>Perfect. Now I have a very simple TypeScript lambda that will automatically run every minute and fetch the current data about each Velib station. Next, I need to store that data somewhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*jbKKYahrP556PsYV.png" /></figure><h3>DynamoDb, a serverless document database</h3><p>DynamoDb is a key/value and document serverless database. The data is stored in <em>tables</em>. Each table contains <em>items</em>, that are simple JSON payloads. For each table, you must define which of the fields of the items will be used as keys, to uniquely identify each item. You can choose between two options:</p><ul><li><strong>a single <em>partition key</em></strong>: for example a country code if you store countries&#39; characteristics. This is like a simple primary key in SQL.</li><li><strong>a <em>partition key</em> and a <em>sort key</em></strong>: for example a stock identifier and a timestamp if you store historical prices for different stocks. This is like a composite primary key in SQL.</li></ul><p>By default, DynamoDb allows you to perform CRUD operations based on the keys you chose for your table. You can also scan all the items or run queries with more complex filters that will, under the hood, also scan the items or leverage the chosen keys if possible. As you pay for each item scanned or queried (more on that later), it’s important to avoid doing full scans of your table. And so, having a sort key is especially useful if you want to be able to fetch your items in a given order. For example, if you want to load the “last” item, you could use the insertion timestamp as the sort key and do a simple query ordered by the timestamp with a limit of 1. Without a proper sort key, you would have to scan through all the items and sort them manually in your code.</p><p>As the choice of keys will impact how the items are <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.Partitions.html">physically stored</a>, changing which fields are used as keys is not possible once you have created a table. You would need to recreate a new table and migrate your data to it.</p><p>But, you can define additional indexes if you often have to query your items using other fields than the keys:</p><ul><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSI.html"><strong><em>Local Secondary Indexes (LSI)</em></strong></a><strong><em> </em></strong>allow you to define an additional sort key, (but you must keep the same partition key).</li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html"><strong><em>Global Secondary Indexes (GSI)</em></strong></a>: allow you to define a whole new pair of partition and sort keys. In fact, a GSI is almost a duplicate of your table, stored differently. That means that a GSI can lag a little behind your main table and is considered only <a href="https://en.wikipedia.org/wiki/Eventual_consistency">eventually consistent</a> with the main table.</li></ul><p>DynamoDb also offers additional quality-of-life features, like automated removal of old items. For that, you need to add a field to your items that will contain the timestamp at which the items should be deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*sVwgcesmW4jGrX6IHkdMsw.png" /><figcaption>A ‘stock’ table with partition and sort keys along with a time-to-live field for automated deletion a year later.</figcaption></figure><h3>DynamoDb pricing or the way of the constant flow</h3><p>As a serverless service, the DynamoDb pricing model is not based on the underlying server instances, but on how you use the service. You pay for the quantity of data you store, and how many read and write operations you perform. More precisely, you have two choices :</p><ul><li><a href="https://aws.amazon.com/dynamodb/pricing/on-demand/"><strong><em>on-demand</em></strong></a>: you pay for the actual number of reads/writes you have done this month</li><li><a href="https://aws.amazon.com/dynamodb/pricing/provisioned/"><strong><em>provisioned</em></strong></a>: you define in advance how many read/write per second your table will need. If you go over, DynamoDb will throw an error stopping you from overconsuming.</li></ul><p>On-demand seems way simpler but is also more costly. For the same number of reads/writes, a provisioned table will cost about x6 less. Furthermore, the free tier for Dynamo only concerns provisioned tables, so that’s what I will use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*0LVaHcKrBcQ-K_8UUkSbqg.png" /><figcaption>The free tier for DynamoDb and Lambda. Note that only “provisioned” tables are covered.</figcaption></figure><p>So, how does this provisioning stuff work, concretely?</p><p>For each table, you need to define the numbers of RCU (Read Capacity Unit) and WCU (Write Capacity Unit). And you can also set up automated scaling of those two properties if you want them to be adjusted automatically up to a given limit.</p><p>Both RCU and WCU represent the number of Reads and Writes your table can sustain per second. To be more precise:</p><ul><li><strong>1 RCU = 1 consistent read of a 4kb item per second. Or 2 non-consistent reads of a 4kb item per second</strong> (DynamoDb use a non-locking replication process under the hood, which means a write operation can take a few seconds to propagate to all the nodes in the cluster. So, depending on your use case, you may absolutely need consistent data, or you may be fine with getting stale data). If you read items with a size of more than 4Kb, you will need 1 RCU for each additional 4Kb block.</li><li><strong>1 WCU = 1 write of a 1kb item per second. </strong>If you write items with a size of more than 1Kb, you will need 1 WCU for each additional 1Kb block.</li></ul><blockquote><strong>Example:</strong> <br>If you read (consistently) two items with a size of 8Kb each, every second, it would take 4 RCU. Reading (inconsistently) the same items would take only 2 RCU. Writing them would take 16 WCU.<br>Sadly, if you read/write an item with a size of 0.01Kb every second, you will still need at least 1 RCU and 1 WCU as 4Kb and 1Kb are the minimal size of a read and write operation respectively.</blockquote><p>But, planning your reads and writes every second seems near impossible. That’s why DynamoDb allows “bursts” of reads and writes. The operations you don’t use can accumulate for up to 300 seconds (5 minutes).</p><blockquote><strong>Example</strong>: <br>With 1 RCUs, if you don’t read anything for 2 minutes (120 seconds), it means you can read (consistently) 120s * 1 RCU * 4Kb = 960Kb worth of data from your table in a short period of time.</blockquote><p>So, if you know in advance the amount of data that will be read from and written to your table about every 5 minutes, you should be able to select the perfect number of RCUs and WCUs. In my case, the data represents an (almost) fixed number of stations and is fetched every minute, so that should be doable.</p><h3>Designing for cost</h3><p>With only 25RCUs and 25 WCUs for the whole application, I really need to optimize each table.</p><p>Let’s look at the first table that will store each station&#39;s content (number of available bikes and status) every minute. How I structure the data (and which keys I choose) will impact the number of RCU/WCU I’ll need.</p><p>So, what keys could I use?</p><p><strong>#1 Using the station code as the partition key and the datetime as the sort key:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*1T6ka9UV-WuXCT1a-bl9Rg.png" /></figure><p>Seems pretty obvious. Accessing a specific station’s content becomes very simple. The problem is that I have ~1.500 stations, and each station’s content represents a very small payload (about 160b). I’ll need to perform ~1.500 writes each time I want to update the content of all the stations. Even with bursting (I only fetch the content every 60s), it would amount to 1.500 / 60 = 25 WCUs!</p><p><strong>#2 Using the datetime as the partition key:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*8YzBnK5SXiXMDLcoMvFjcg.png" /></figure><p>To minimize the number of write operations needed, I could store every station’s content as a single object (using a JavaScript dictionary). That way I’ll end up with a big 230Kb object (below the 400Kb size limit of DynamoDb) and I will better use my RCUs and WCUs. But partition keys cannot be used to sort data, and that means I could not efficiently get the last updated content.</p><p><strong>#3 Using just the datetime as the sort key</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*KsKvUfMkvLPHl1E7tYgnZQ.png" /></figure><p>This is technically forbidden, as a partition key is mandatory. But nothing prevents me from using a simple constant as the partition key. That way, I can have the same size optimization as for solution #2, and I can easily sort based on the datetime.</p><p>To be fair, this is not a good solution in terms of performance. Having a single partition means DynamoDb will not be able to distribute my data optimally. But cost is my most important constraint here.</p><p>Let’s recap the different characteristics of each solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQZ-OABkvLn31wC0yWffPQ.png" /><figcaption>Differents solutions for storing each station’s content, and their respective costs and characteristics</figcaption></figure><p>Solution #3 is the obvious winner.</p><p>Creating the table takes only a few seconds using the AWS web console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*IBjut6m9QLeR6sgwkcz2mw.png" /></figure><p>I won’t details how to write a DynamoDb repository in TypeScript, as the <a href="https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-document-client.html">official SDK documentation</a> is already quite complete. Just be careful when marshaling/unmarshalling from a TypeScript object to a JSON. <a href="https://www.npmjs.com/package/type-transformer">Type-transformer</a> can be useful for that. And don’t forget to attach the correct roles to your function so that it can access your table.</p><p>And it works! The Write capacity used is just below the 4 WCU that I defined for this table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Fa5G_xaMjCfdXsflE-dcOQ.png" /><figcaption>Provisioned VS Consumed WCUs</figcaption></figure><p>Those cost concerns introduced a major shift between how “events” were implemented in my first Kafka prototype and how they are done in the Serverless solution: before, with Kafka, I could afford to have one event for each station, resulting in about 1.500 events per minutes. Now, one event represents the whole network of stations.</p><h3>Computing the delta</h3><p>I will do one last thing in the <em>FetchStationsContent </em>function<em>.</em></p><p>I will compute, for each station, the difference between the number of bikes in the station now and the number of bikes a minute ago and I will include it in the content data. If nothing happened to a given station, I will also compute the last time it saw some activity. This <em>inactiveSince </em>attribute will get compounded as long as a station has no activity.</p><p>That way, the content will no longer represent the state of the stations at a given time, but also what happened to those stations (was a bike rented or returned? since when did it stop moving?).</p><p>To do that, I need to fetch the current stations’ content (with the Axios client) and the last inserted content in my Dynamo table (with the Dynamo repository). Here, my Dynamo sort key will come in especially handy to avoid scanning my whole table. Those two operations can be done in parallel using <em>Promise.all</em> and once both are finished I can compute the delta.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1e85138cdfc99da910c9a345f63b91a/href">https://medium.com/media/b1e85138cdfc99da910c9a345f63b91a/href</a></iframe><h3>Infrastructure as code</h3><p>The work on the other function, <em>FetchStationsCharacteristics</em>, is very similar. I need to create a function, upload some code, create an EventBridge rule, create a table and attach the correct roles to the function.</p><p>Already we see a limitation of the serverless approach: instead of having a few “big” applications, we need to create many small functions and for each one, we need to define the correct infrastructure.</p><p>Using the AWS web console is fine for the first time, but this does not scale. Am I supposed to manually create tens of functions and tables? What if I want to change some common characteristics of all my functions? How can I easily roll back an infrastructure change? This can get ugly fast. Fortunately, several tools are here to help me.</p><p><a href="https://aws.amazon.com/cloudformation/">CloudFormation</a> is an AWS service that allows to define, in YAML or JSON, the different resources needed for an application and, even better, to create and update those resources as necessary. Need a new function and a new DynamoDb table? Just add them to your CloudFormation file (or <em>template</em>), deploy it and everything will be created or updated accordingly.</p><p>Here is an example of a template defining a single Lambda function, a DynamoDb table, and the needed role for the function to update and query the table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bea2192a29019670122e71e722b7cf9f/href">https://medium.com/media/bea2192a29019670122e71e722b7cf9f/href</a></iframe><p>Defining the function and table is quite straightforward, but defining the role takes some work.</p><p>Fortunately, we can simplify that using SAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XhYvURbfqG6uw_MRAdslQ.png" /><figcaption>SAM, the Serverless Application Model</figcaption></figure><p><a href="https://aws.amazon.com/serverless/sam/">SAM</a>, or the Serverless Application Model, is an open-source framework used to build serverless applications on AWS (and developed by AWS). It consists of two things:</p><ul><li>An extension of CloudFormation, offerings simplified resources for the most common serverless services</li><li>A CLI, that allows you to build, test locally and deploy your application</li></ul><p>Thanks to SAM’s simpler resources, the same Lambda function, and DynamoDb table can be described as such:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88124457f58cc050e55cf75ce12723bc/href">https://medium.com/media/88124457f58cc050e55cf75ce12723bc/href</a></iframe><p>No more role to painstakingly define. SAM will translate the simplified template into a fleshed-out CloudFormation template and create the needed roles. And, you can still use “full-blown” CloudFormation resources in the same template if you need it.</p><p>To build and deploy my two functions and their corresponding tables, I just need to write the SAM template and run the following commands.</p><pre>sam build<br>sam deploy</pre><p>And it won’t work… Because SAM does not really know how to handle the TypeScript compilation process. There are several solutions to address that. I could create a <a href="https://evilmartians.com/chronicles/serverless-typescript-a-complete-setup-for-aws-sam-lambda">dedicated Layer</a> (a way to add additional capabilities to your Lambda). But I found it easier to use <a href="https://www.npmjs.com/package/aws-sam-webpack-plugin">sam-webpack-plugin</a>.<br>So, now my process will be:</p><pre>npm run build<br>sam deploy</pre><p>This will transpile my TypeScript functions into JavaScript, upload the source code to an S3 bucket, transform the simplified SAM template to a full CloudFormation template and deploy everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDBsy7xPv2mNnElZ7XNVqg.gif" /><figcaption>The build and deployment process</figcaption></figure><p>And I can sip my coffee as my new functions and tables are created.</p><blockquote>Other tools exist to ease up serverless applications development. For example, <a href="https://www.serverless.com/">Serverless</a> offers similar features to SAM, while allowing you to work with other cloud providers. It also offers more powerful testing and alerting functionalities.</blockquote><p>That’s a good start. Now that I’m able to store the content of each station over time, I should be able to compute the usual activity of a given station and use that to detect when a station seems locked.</p><p>See you in part 3!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*tJfd4EEKVAwUKpMa" /></figure><ul><li><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Part 1</a>: Choosing the AWS serverless stack for a prototype</li><li><a href="https://ouvreboite.medium.com/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699">Part 2</a>: The backbone of a serverless app: Lambda functions and DynamoDb tables</li><li><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-3-d532318dfca7">Part 3</a>: Implementing a real-time detection algorithm with Lambda functions and DynamoDb streams</li><li><a href="https://ouvreboite.medium.com/creating-a-serverless-api-and-hosting-a-frontend-with-s3-b50e61a8f707">Part 4</a>: Creating a serverless API and hosting a frontend with S3</li><li><a href="https://medium.com/codex/performance-tuning-for-an-aws-lambda-based-api-b8b49b2d07db">Part 5</a>: Performance tuning for a Lambda-based API</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1967d639699" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699">The backbone of a serverless app: Lambda functions and DynamoDb tables</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the AWS serverless stack for a prototype]]></title>
            <link>https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649?source=rss-475d24faa679------2</link>
            <guid isPermaLink="false">https://medium.com/p/95dcdb477649</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[velib]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Jean Baptiste Muscat]]></dc:creator>
            <pubDate>Tue, 29 Jun 2021 12:07:04 GMT</pubDate>
            <atom:updated>2021-11-22T21:03:22.341Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Choosing the AWS serverless stack for a prototype (Detecting Paris’ locked bicycle stations 1/5)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vy9KxwnX7Z6hooQYkiQ-2w.jpeg" /><figcaption>Photo by Guillaume Bontemps / Ville de Paris</figcaption></figure><blockquote>This series of articles is about me spending way too much time trying to solve a niche problem (detecting locked bicycle stations in Paris) while learning how to use the AWS Serverless stack. To find the other articles, skip to the bottom of the page.</blockquote><h3><strong>Lockdown and dead stations</strong></h3><p>Paris, May 2020, end of the first lockdown. I decide to join some of my friends for a picnic. So, like many Parisians, I’m headed toward the Bois de Vincennes, Paris’ largest public park, on the eastern edge of the city.</p><p>The weather is perfect for a short bike ride and I quickly rent a Velib, one of the many public bikes that can be rented and returned in any of the 1500 stations scattered across the city. Arriving near the park, I look at the official app to find the nearest station with available slots to return my bike. As I approach, something seems off. I see several people, puzzled, trying to rent or return a bike. I sigh. The station is locked. Dead.</p><blockquote>Velib was created in 2007 and quickly proved successful, becoming one of the most used bike sharing platforms in the world. In 2017, after the end of the initial 10 years contract, the city chose a new operator to manage and develop the network. And let’s just say the change was not smooth. Three years later the main problems have been solved but, still, Velib users face two common hurdles: the broken bikes that are not removed from the stations (whoses seats are returned by the disapointed cyclist to kindly warn the next user) and, more rarely, stations that are “locked” for a few hours, without notice on the official app or website.</blockquote><p>After finding another station, I join my friends and wash away my misadventure with a cold beer. But I can’t stop thinking about it. It’s not the first time I had to find another station because one was unusable. Why didn’t the official app show the station as dead? Isn’t it easy to detect a station that suddenly stopped renting or returning bikes? How hard could it be with the proper data?</p><h3><strong>The Velib API</strong></h3><p>Luckily Velib exposes a <a href="https://www.velib-metropole.fr/donnees-open-data-gbfs-du-service-velib-metropole">public API</a>. The same data can also be found in the Paris <a href="https://opendata.paris.fr/pages/home/">OpenData</a> project which incorporates and exposes a lot of public data about Paris (if you ever looked for the dataset of every one of the 200.000 trees in Paris, it’s <a href="https://opendata.paris.fr/explore/dataset/les-arbres">there</a>!).</p><p>The API is quite simple, with two main endpoints:</p><ul><li><strong>/station_status.json</strong> which returns, in “real-time” (refreshed every minute) the content and status of each station.</li><li><strong>/station_information.json</strong> which returns the geo-coordinates and name of each station.</li></ul><pre>//station_status.json simplified structure<br>{<br>  &quot;data&quot;: {<br>    &quot;stations&quot;: [<br>      {<br>        &quot;is_installed&quot;: 0,<br>        &quot;is_renting&quot;: 0,<br>        &quot;is_returning&quot;: 0,<br>        &quot;num_bikes_available_types&quot;: [<br>          {<br>            &quot;ebike&quot;: 0,<br>            &quot;mechanical&quot;: 0<br>          }<br>        ],<br>        &quot;num_docks_available&quot;: 0,<br>        &quot;station_id&quot;: 0<br>      }<br>    ]<br>  }<br>}</pre><pre>//station_informations.json simplified structure<br>{<br>  &quot;data&quot;: {<br>    &quot;stations&quot;: [<br>      {<br>        &quot;lat&quot;: 0,<br>        &quot;lon&quot;: 0,<br>        &quot;name&quot;: &quot;string&quot;,<br>        &quot;station_id&quot;: 0<br>      }<br>    ]<br>  }<br>}</pre><p>I could have wished for a little more. For example, an endpoint that would return the past activity of a given station. Or maybe a callback endpoint that would warn me every time a bike is rented or returned to a station.<br>But this is fine. With enough time, I can collect the minute-to-minute activity of each station by polling the <em>/station-status</em> endpoint continuously and feeding some kind of database. And by knowing the past activity of each station, I should be able to know when a station stopped renting or returning a bike for too long and flag it as “locked”. Easy, right?</p><p>I’ve been wanting to learn more about Kafka and event-driven architecture for a long time. And ingesting and processing each update of the <em>/station-status</em> endpoint seems like a good fit for this technology. So, Kafka, it will be.</p><h3>One event at a time</h3><p>First, a quick Kafka refresher.</p><blockquote>Kafka is a scalable persistent event log system that was orignially developed at LinkedIn and has since been open sourced. Some of its original developers left LinkedIn to create <a href="https://www.confluent.io/">Confluent</a>, a company dedicated to improving the Kafka ecosystem.</blockquote><p>You can interact with Kafka in two ways. By being a “producer” which sends new events to be appended to a log (a “topic”). Or by being a “consumer”, that will receive the events from the topic. Contrary to a message queue, the events are not sent synchronously to the consumers. They are stored in the log and can be consumed now or later. Kafka keeps track of what is the last event received by each consumer, allowing them to consume the events in their own time, at their own rate. If a consumer fails to process an event, the event itself is not lost and can be retried.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYY1QvPpgNcQD7N1ork8-w.gif" /><figcaption>A Kafka topic with multiple consumers</figcaption></figure><p>This is with only one topic. But nothing prevents a consumer from also being a producer for another topic. That way you can architecture an application that reacts to a single source event, triggering in cascade different services. This sort of network of topics, consumers, and producers is called a topology in the Kafka world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3NuOe5WshNlPwPMbwuRWQ.gif" /><figcaption>Fictional Kafka topology: Youtube’s video import process</figcaption></figure><p>Each of these services is independent. They can be written in different languages. They can be “real-time”, recurrent batches, or one-time exports. They can be scaled on their own.</p><p>Still, all those services need to interact with Kafka and often do similar things: group events by a given attribute, discard some of them, …</p><p>So it’s no surprise to find specific tools that have been created to take care of those common tasks. They go from lightweight libraries like <a href="https://faust.readthedocs.io/en/latest/">Faust</a> (python) or <a href="https://kafka.apache.org/documentation/streams/">Kafka Streams</a> (java) to full platforms like <a href="https://flink.apache.org/">Flink</a>. As I have some experience with Java, I’ll pick Kafka Streams.</p><blockquote>Event driven architecture is not just a Kafka thing. Others tools can be used or even mixed with Kafka. Flink, for example, support a variety of event sources and sinks.</blockquote><h3>The cost of Kafka</h3><p>With all that new knowledge, I can start building a <a href="https://github.com/ouvreboite/velinfo_kafka_prototype">small application</a> able to ingest the Velib API data and process it to detect (very imprecisely) the locked stations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOBUeN_HPwnOAjJqGHhgZA.png" /><figcaption>The Kafka-based prototype architecture</figcaption></figure><p>After a few weeks, this application quickly grows to a sizeable Kafka+KafkaStream+PostgreSQL+SpringBoot+Thymeleaf mess. The whole infrastructure being created from a single Docker Compose file makes development easy.</p><p>To be more in tune with Kafka’s “event log” philosophy, it first transforms the /station-status payload into station-by-station incremental updates. This essentially allows me to design the rest of the application as if I could subscribe to a Velib endpoint that would warn me each time a bike is rented or returned to a specific station. From that, it computes hour-by-hour usage statistics for each station and feeds a SQL database that is itself used for the locked station detection. It also tries to detect individual broken bikes but without much success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*lxCV2nXTsRYwERrB6ldejw.png" /><figcaption>Simplified Kafka topology</figcaption></figure><p>The resulting Kafka topology is quite simple (Kafka Stream creates additional hidden topics to maintain its inner state). Overall a little more than 10 topics are used. It “works”. But each time I switch off my computer or the application itself, I create gaps in my hour-by-hour statistics database. It’s time to deploy to production.</p><p>This should be simple, as I only need a small Kafka cluster with ~10 topics and minimal replication, a small SQL instance and one or two servers to run the rest. As learning more about AWS was also on my 2020 wish list, I will try to leverage only AWS services.</p><p>Let’s start with the Kafka cluster. What kind of offering is there?</p><ul><li><strong>Fully managed</strong>: I could use <a href="https://aws.amazon.com/msk/">AWS MSK</a>. The smallest instance (Kafka.t3.small) cost 0,0456 USD per hour. I need to run it full time, so that means… $400 per year</li><li><strong>Self-managed</strong>: I could just use an <a href="https://aws.amazon.com/ec2/">AWS EC2</a> instance with ~2GB of memory and install Zookeeper and Kafka on it. A t2.small cost 0,023 USD per hour, $200 per year.</li><li><strong>Container</strong>: I could also leverage Docker and use a similar EC2 instance as part of <a href="https://aws.amazon.com/ecs">AWS ECS</a>. That would simplify the setup but still be $200 per year.</li><li><a href="https://aws.amazon.com/kinesis/"><strong>AWS Kinesis</strong></a>: it’s very similar to Kafka, it’s fully managed, it seems way cheaper. But it’s not compatible with Kafka Stream, which would mean rewriting a big part of the application and choosing a new streaming framework.</li><li><strong>Raspberry Pi</strong>? I already have a Raspberry Pi lying around somewhere. I could surely install my Kafka cluster on this, open the right ports on my home gateway and host the rest of the application on AWS. I would also need to pray to the computing gods that nothing bad happens while I’m not home to fix it.</li></ul><p>It seems I have a choice between spending way more than I was expecting (and it’s just for the Kafka cluster) or massively reworking my application. Maybe the real problem is not the cost of Kafka. Maybe it is that I should have taken my constraints into account when choosing my architecture.</p><h3><strong>Back to the drawing board</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tLm03ilAB4h2E5dq" /><figcaption>Photo by <a href="https://unsplash.com/@diana_pole?utm_source=medium&amp;utm_medium=referral">Diana Polekhina</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>What do I expect from this project? What does the result should look like?</strong></p><ul><li>It should run “in production”, on AWS.</li><li>Velib works 24/7, so should my application.</li><li>I want to spend 200€ max per year if I have less than 100 monthly users.</li><li>The day-to-day operations should be minimal.</li><li>The UI should look OK.</li></ul><p><strong>To ease my burden, I’ll also define what I don’t expect from this project.</strong></p><ul><li>Kafka is not mandatory. At this point, I feel like I have already learned a lot about it, and would rather focus on delivering something.</li><li>The locked station detection does not need to be accurate. I don’t even know if the Velib API’s data are accurate.</li><li>The quality of code is not my concern. I’m more interested in the architecture and learning more about AWS.</li><li>The UI will be french only, as Velib only operate in Paris.</li><li>Nothing fancy for the front end. I’m already familiar with Angular, so that will be enough.</li></ul><p>If my little experiment with Kafka has taught me one thing, I need to better understand the AWS offering and its pricing if I want to stay within my budget. So I’ll take some time off to learn about it.</p><h3>λ function</h3><p>AWS is a big topic. New services are added every year, and it’s easy to get lost when trying to learn about it. To help me focus on what are supposed to be its most important services for application development, I decided to pass the <a href="https://aws.amazon.com/certification/certified-developer-associate/">AWS Certified Developer Associate</a> certification. It took me a couple of months, but I felt way more confident on what could be done using AWS and at what cost. And it allowed me to discover the serverless offering of AWS.</p><blockquote>Having already a side project in mind helped extract the most of what I learnt along the way. So if you intend to pass this certification, I can only recommend you to have already some kind of project that you want to “migrate” to AWS</blockquote><p>So what is this serverless stuff? There must be some servers somewhere, right?</p><p>Let’s say you want to create some kind of simple web API. A single endpoint, GET <em>/something</em>, coded in JavaScript using NodeJs/Express.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*3zL9nOVcb9actL_aHZtZqg.gif" /></figure><p><strong>Self-managed:</strong> you rent a “server”, for example, an EC2 instance from AWS. This instance lives in your private network inside AWS (your <a href="https://aws.amazon.com/vpc/">VPC </a>or “Virtual Private Cloud”). On this instance, you are free to install whatever you want. For example NodeJs. You then upload your application source code/package/compiled artifact that will run using the runtime you installed.</p><p>If you want to scale your application, you can rent several EC2 instances and use a load balancer to dispatch incoming requests to them. You need to set up each one of them similarly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*n6m6YY3hHtJ-miYMe8yAvw.gif" /></figure><p><strong>Container platform:</strong> to make scaling easier and simplify the creation of new instances, you can use containers. Either by manually installing a container service on each EC2 instance or by using a container platform like ECS. This platform will manage the provisioning of the EC2 instances for you. You just need to provide the container and specify the number of instances to be run.</p><p>But, in the end, you still own those instances, they are part of your EC2 fleet and you can manually connect to them.</p><p><strong>A quick note on auto scaling groups:</strong> the number of instances you use can be set manually or automatically, using an autoscaling group. You will create a rule that defines how and within which boundaries should the number of instances evolve. CPU or memory usage is often used to trigger this kind of scaling. Such a rule could be :</p><blockquote>“If my instances’ CPU &gt; 80% then increase the number of instances up to 10. I my instances’ CPU &lt; 30% then decrease the number of instances down to 1”.</blockquote><p>The key point is that you always need at least one instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*OemqkRM_w6X0N0oqbLJDyA.gif" /></figure><p><strong>Lambda</strong>: AWS Lambda is a serverless computing platform. Instead of coding a full application, you divide it into smaller “functions” that can each be called independently.</p><p>Each function can be seen as a small script that is supposed to run for a few seconds or minutes and perform a specific task. For example, you could have a function in charge of answering to GET <em>/something</em>.</p><p>When a Lambda is triggered, an available server instance is taken from a global pool. Your source code is deployed to it and run. Then your code is removed and the instance is freed up.</p><p>A very simple Lambda function code can look like this:</p><pre>//a basic javascript lambda performing a REST call<br>const https = require(&#39;https&#39;)<br>let url = &quot;<a href="https://docs.aws.amazon.com/lambda/latest/dg/welcome.html">https://e</a>xample.com&quot;</pre><pre>exports.handler = async function(event) {<br>  const promise = new Promise(function(resolve, reject) {<br>    https.get(url, (res) =&gt; {<br>        resolve(res.statusCode)<br>      }).on(&#39;error&#39;, (e) =&gt; {<br>        reject(Error(e))<br>      })<br>    })<br>  return promise<br>}</pre><p>So your function still runs on a server. But you don’t know which one, and you don’t care.</p><p><strong>What about cost?</strong></p><p>For the <em>Self Managed</em> and <em>Container Platform</em>, it’s quite easy: each instance type as an hourly cost. For Lambdas it’s a little bit more complicated: each invocation cost $0.0000002 ($0.20 per million)+ $0.0000000021 per milliseconds of execution time for a basic Lambda, up to $0.0000001667 per milliseconds for the biggest one. More on Lambda performance in a later article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZxlMPHN-hshl6XaDeNIzQ.png" /><figcaption>Cost comparison between the smallest EC2 instance and the smallest Lambda</figcaption></figure><p>The biggest takeaway is that a Lambda, unused, costs nothing. So, for my project with a very limited audience and peak usages around 8 AM and 5 PM, using Lambdas instead of having an EC2 instance twiddling its thumbs most of the time makes sense.</p><h3>The serverless offering</h3><p>The same principles can be applied to more than computation :</p><ul><li>A database? DynamoDb (you pay for the number of items created/read)</li><li>A file server? S3 (you pay for the number of files created/read)</li><li>A load balancer/router? API Gateway (you pay for the number of requests being routed)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXQjK4Uoyu7R-z2uu5bqVA.png" /><figcaption>The current AWS serverless offering</figcaption></figure><p>All those services still rely on servers, but those servers are abstracted from the client and the pricing is derived from the usage instead of the infrastructure.</p><p>They can be used alongside a classic application. But you can also design complex applications using only serverless services. And what makes everything things stick together are the Lambda functions. Or, more exactly what triggers the functions.</p><p>A REST call? A file being pushed to S3? A new message sent in SQS? A new event in a Kafka topic? Almost any AWS service can trigger a Lambda function. And AWS provides event managers (like EventBridge) and schedulers (like Step Functions) for more complex use cases.</p><p>Some triggers are very simple (“fire and forget”), but others can be more complex. For example, DynamoDb (a serverless document database) can publish events (object inserted/updated/deleted) as a “stream” that can itself trigger a function. Each function subscribing to a Dynamo Stream will have its own queue for events to pile up and can process those events at its rhythm. And if a lambda invocation fails, the event is kept to allow for retries. Sound a little bit like Kafka, no?</p><p>So combining DynamoDb and Lambda, I can recreate the same kind of “topology” as my first Kafka prototype.</p><blockquote>Side note. The real “serverless” Kafka at AWS is Kinesis. But, in 2020, DynamoDb only supported publishing events in DynamoDb Stream. The support for Kinesis publication from DynamoDb has been added in 2021.</blockquote><p>Let’s go back to the cost. One thing I did not mention in my initial discussion about the cost of a Kafka cluster is the <a href="https://aws.amazon.com/free">AWS Free Tier</a>.</p><p>To attract new clients, AWS has free offers on some of its services. For example, you can have a small EC2 instance “for free”, but only for the first year. Luckily for me, the Lambda and DynamoDb offers are quite generous and, most importantly, they do not expire.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*jFyJUx25edUZZ0uMODYbUg.png" /><figcaption>AWS Free Tier for Dynamo and Lambda</figcaption></figure><p>So the plan is simple: re-architecture my application to leverage the AWS serverless services (mainly Lambda and DynamoDb) while staying within the constraints of the free tier.</p><p>See you in <a href="https://ouvreboite.medium.com/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699">Part 2</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*eVTuOt5mGhzMcNmQ" /></figure><ul><li><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Part 1</a>: Choosing the AWS serverless stack for a prototype</li><li><a href="https://ouvreboite.medium.com/detecting-locked-bicycle-stations-an-aws-serverless-story-part-2-b1967d639699">Part 2</a>: The backbone of a serverless app: Lambda functions and DynamoDb tables</li><li><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-3-d532318dfca7">Part 3</a>: Implementing a real-time detection algorithm with Lambda functions and DynamoDb streams</li><li><a href="https://ouvreboite.medium.com/creating-a-serverless-api-and-hosting-a-frontend-with-s3-b50e61a8f707">Part 4</a>: Creating a serverless API and hosting a frontend with S3</li><li><a href="https://medium.com/codex/performance-tuning-for-an-aws-lambda-based-api-b8b49b2d07db">Part 5</a>: Performance tuning for a Lambda-based API</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95dcdb477649" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/detecting-locked-bicycle-stations-an-aws-serverless-story-part-1-95dcdb477649">Choosing the AWS serverless stack for a prototype</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>