<?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 Jon Humble on Medium]]></title>
        <description><![CDATA[Stories by Jon Humble on Medium]]></description>
        <link>https://medium.com/@jon.humble?source=rss-dacaf5d97315------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_7zwb2ZV-nuRw84IdBN6Vw.jpeg</url>
            <title>Stories by Jon Humble on Medium</title>
            <link>https://medium.com/@jon.humble?source=rss-dacaf5d97315------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 16:17:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jon.humble/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[Clear and concise logging in Scala.]]></title>
            <link>https://engineering.depop.com/clear-and-concise-logging-in-scala-342627ad72ba?source=rss-dacaf5d97315------2</link>
            <guid isPermaLink="false">https://medium.com/p/342627ad72ba</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Jon Humble]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 10:58:38 GMT</pubDate>
            <atom:updated>2022-01-27T10:58:38.296Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clear and concise logging in Scala</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAyojUgI5vZ_tlTLtbJBiQ.jpeg" /><figcaption><a href="https://www.flickr.com/photos/8070463@N03/18039433124">“Two wolves posing on the log”</a> by <a href="https://www.flickr.com/photos/8070463@N03">Tambako the Jaguar</a> is licensed under <a href="https://creativecommons.org/licenses/by-nd/2.0/?ref=openverse&amp;atype=rich">CC BY-ND 2.0</a></figcaption></figure><p>As I was working on a new Pricing Service for the <a href="https://www.depop.com/">Depop</a> backend the other day, I realised that it needed more logging. A <em>lot</em> more to be honest.</p><p>The Pricing Service will serve to supply prices for all of the products on Depop’s market to our internal services and it is vital that we can see the logs of how it is working.</p><p>Logging is one of those things — along with unit testing and <a href="https://engineering.depop.com/monitoring-depop-d5331573b13e">monitoring</a> — that ought to be woven into the writing of the code, but often gets relegated until after the core functionality is written.</p><p>Admonishing myself, I set about examining the program for places where logging would most illuminate the progress of the price calculation and in particular, the places where things might go awry.</p><p>As I did this I noticed a couple of things…</p><h4>The code got uglier</h4><p>In <a href="https://scala-lang.org/">Scala</a>, the last value calculated in a function <em>is</em> the return value. <br>This leads to concise code like:</p><pre>val <em>calculatePrice </em>= (price: Price)                      =&gt;<br>                     (maybeShippingPrice: Option[Price]) =&gt;<br>  maybeShippingPrice.map(p =&gt; p + price)</pre><p>However, with logging, it gets a lot bulkier:</p><pre>val <em>calculatePrice </em>= (price: Price)                      =&gt;<br>                     (maybeShippingPrice: Option[Price]) =&gt; {<br>  <strong>val</strong> maybeTotal = maybeShippingPrice.map(p =&gt; p + price)<br>  <strong>if (maybeTotal.isEmpty) {<br>    <em>logger</em>.info(&quot;No shipping price available&quot;)<br>  }<br>  maybeTotal</strong><br>}</pre><h4>There was a pattern to the logging</h4><p>I kept coming across the same pattern in logging as we see above — in general:</p><pre>def exampleFunction[T](arg: T): String = {<br>  val result = <em>calculateStringFromT</em>(arg)<br>  if (someTestOn(result)) {<br>    <em>logger</em>.error(s&quot;The test on result was true - arg was [<strong>$</strong>arg]&quot;)<br>  }<br>  result<br>}</pre><p>This was screaming out for generalisation.</p><p>Also, it would be great if we could make it look less ugly¹.</p><h3>The types involved</h3><p>Breaking down our exampleFunction, we have:</p><ul><li>A result</li><li>A condition for logging based on the result</li><li>A means of logging a string</li><li>A string to log</li></ul><p>The result could be anything, so let’s denote this by the type variable T.</p><p>The condition is a <a href="https://www.baeldung.com/cs/predicates">predicate</a>:</p><p>type LoggingPredicate[T] = T =&gt; Boolean</p><p>The means of logging is a procedure² that takes a String:</p><p>type Logger = String =&gt; Unit</p><p>The String that is logged is calculated from the result and may use the variables available at the time. If this function is defined within the function to be logged, it will have access to the local variables, so all we need is:</p><p>type MessageGen[T] = T =&gt; String</p><h3>A first stab at a logging function</h3><p>Given these types, we can start to build a logging function:</p><pre>def log[T]( t         : T,<br>            shouldLog : LoggingPredicate[T],<br>            logger    : Logger,<br>            msgGen    : MessageGen[T] ): T = {<br>  if (shouldLog(t)) logger(msgGen(t))<br>  t<br>}</pre><h4>Improving things with Partial Functions</h4><p>We can combine the functionality of the logging predicate and the message generator by making the message generator a <a href="https://www.baeldung.com/scala/partial-functions"><em>partial function</em></a><em>:</em></p><pre>type MessageGen[T] = PartialFunction[T, String]</pre><p>A partial function is only defined for a subset of its possible inputs. We use this to log the String it returns when it is defined and skip logging when it’s not:</p><pre>def log[T]( t     : T,<br>            msgGen: MessageGen[T],<br>            logger: Logger ): T = {<br>  msgGen.<strong>lift(t).foreach(msg =&gt; logger(msg))</strong><br>  t<br>}</pre><p>We don’t want to get an exception if the partial function is not defined, so we call lift(t) on it. This converts the partial function to a plain function that returns None if the parameter passed is not in the domain of the partial function and Some(msg)if it is. Only in the case of the latter is the logger called.</p><h3>Using the logging function</h3><p>Let’s see how this looks from the client’s point of view by revisiting the earlier example.</p><p>First, let’s set up some Loggers³</p><pre>val <em>info    </em>: Logger = s =&gt; <em>logger</em>.info(s)<br>val <em>warning </em>: Logger = s =&gt; <em>logger</em>.warn(s)<br>val <em>error   </em>: Logger = s =&gt; <em>logger</em>.error(s)</pre><p>Now we can update the example function to use our new log function:</p><pre>def exampleFunction[T](arg: T): String = {<br>  val result = <em>calculateStringFromT</em>(arg)<br>  <strong>val msgGen: MessageGen[String] = {<br>    case &quot;&quot; =&gt; s&quot;The result was empty - arg was [$arg]&quot;<br>  }</strong><br>  <strong><em>log</em>(result, msgGen, info)</strong><br>}</pre><p>Notice how MessageGen now being a partial function enables elegant implementation using pattern matching syntax.</p><p>If we also move it outside the function, we can clarify things even more:</p><pre>private def msgGen[T](t: T): MessageGen[String] = {<br>  case &quot;&quot; =&gt; s&quot;The result was empty - arg was [<strong>$</strong>t]&quot;<br>}<br><br>def exampleFunction[T](arg: T): String = {<strong><br>  val result = <em>calculateStringFromT</em>(arg)<br>  <em>log</em>(result, <em>msgGen</em>(arg), <em>logger</em>.info)<br></strong>}</pre><p>Now it’s starting to look better! However the log function does not communicate its intent well to a human reader. What we are trying to say, in English, is:</p><pre>Log this item using this message generator at level info, then return it.</pre><p>Let’s see if we can craft a more <a href="https://www.martinfowler.com/bliki/FluentInterface.html">fluent interface</a> to express this clearly.</p><h4>Some <a href="https://www.computerhope.com/jargon/s/syntactic-sugar.htm">syntactic sugar</a> to improve readability</h4><p>To improve the readability of this code, we are going to use two tools — <a href="https://www.geeksforgeeks.org/currying-functions-in-scala-with-examples/">currying</a> and <a href="https://docs.scala-lang.org/overviews/core/implicit-classes.html">implicit classes</a>.</p><p>First, let’s curry the log function:</p><pre>def log[T](t: T): MessageGen[T] =&gt; Logger =&gt; T = {<br>                  msgGen        =&gt; logger =&gt;<br>  msgGen.lift(t).foreach(msg =&gt; logger(msg))<br>  t<br>}</pre><p>Currying the log function has changed it from a function that takes three parameters and returns a value T, to a function that takes one parameter and returns another function of MessageGen[T] =&gt; Logger =&gt; T</p><p>So now instead of calling:</p><pre><em>log</em>(result, <em>msgGen</em>(arg), <em>logger</em>.info)</pre><p>We call:</p><pre>log(result)</pre><p>and defer the supplying of the rest of the parameters for later.</p><p>This takes advantage of the fact that in functional programming languages, functions <em>are</em> values. Given that, we can now use an implicit class to <em>add functions</em> to this type:</p><pre>implicit class MessageGenOps[T](f: <strong>MessageGen[T] =&gt; Logger =&gt; T</strong>) {<br>  def using(msgGen: MessageGen[T]): Logger =&gt; T = f(msgGen)<br>}</pre><p>Note the implicit class takes a single parameter of the<em> type returned </em>by our<em> </em>curried log <em>function</em>. This lets us call the defined function — using — on the return value of log, making a chain of calls typical for a fluent interface:</p><p>log(item).using(msgGen)</p><p>Having supplied the MessageGen parameter of the log method’s return type, we’re now left with Logger =&gt; T.</p><p>So we make another implicit class:</p><pre>implicit class LoggerOps[T](f: <strong>Logger =&gt; T</strong>) {<br>  def atLevel(logger: Logger): T = f(logger)<br>}</pre><p>Now we can write log(item).using(msgGen).atLevel(info) which is almost there, we just need one more implicit class:</p><pre>implicit class SelfHelper[T](t: <strong>T</strong>) {<br>  def andReturnIt: T = t<br>}</pre><p>This may seem like an odd class — it has no functionality! It does, however, let us complete our fluent chain of calls gracefully:</p><pre>log(item).using(msgGen).atLevel(info).andReturnIt</pre><p>Compare this with our English sentence:</p><pre>Log this item using this message generator at level info, then return it.</pre><p>Pretty close, eh?</p><h3>Logging parameterised types</h3><p>Going back to our original motivating example, let’s add logging to it using our new functionality:</p><pre>val msgGen: MessageGen[Option[Price]] = { <br>  case Some(price) if price&gt; 50 =&gt; &quot;Expensive shipping<strong>&quot;<br></strong>}</pre><pre>val <em>calculatePrice </em>= (price: Price)                      =&gt;<br>                     (maybeShippingPrice: Option[Price]) =&gt; {<br>  val maybeTotal = maybeShippingPrice.map(p =&gt; p + price)<br><strong>  log(maybeTotal).using(msgGen).atLevel(info).andReturnIt</strong><br>}</pre><p>Here, we are logging a value of type Option[T]. This is a <em>parameterised</em> type, often referred to as generic⁴<em>.</em></p><p>Note the predicate price &gt; 50 is really on the inner Price value, but since log is typed:</p><pre>def log[T](t: T): MessageGen[T] =&gt; Logger =&gt; T</pre><p>this binds T to Option[Price], so we need to define our message generator as MessageGen[Option[Price]].</p><p>It is simple enough to unwrap the Option, in this case, but it would get more annoying for List and other collections.</p><p>There is an important type where this approach won’t work at all, though.</p><h4>Future</h4><p>A <a href="https://alvinalexander.com/scala/concurrency-with-scala-futures-tutorials-examples/">Future</a> represents a value that is still in the process of being calculated. We cannot create a MessageGen[Future[T]] because it will block until the future value is populated.</p><p>Fortunately, it turns out that Future has a function that will accept a procedure as a parameter and execute it once the value is generated:</p><pre>def foreach[U](f: (T) =&gt; U)<br>              (implicit executor: <a href="https://www.scala-lang.org/api/current/scala/concurrent/ExecutionContext.html">ExecutionContext</a>): <a href="https://www.scala-lang.org/api/current/scala/Unit.html">Unit</a></pre><p>This suggests we should be able to create a logging function for Future using foreach:</p><pre>def logF[T](ft: Future[T])(implicit ec: ExecutionContext):<br>  MessageGen[T] =&gt; Logger =&gt; Future[T] = {<br>  msgGen        =&gt; logger =&gt; {<br>    <strong>ft.foreach</strong>(t =&gt; msgGen.lift(t).foreach(msg =&gt; logger(msg)))<br>    ft<br>  }<br>}</pre><p>Once the Future resolves, it will call the function passed to foreach and log <em>if</em> the future value is in the domain of msgGen.</p><h4>A logger for parameterised types</h4><p>We can try to generalise this future logger to all single parameter types :</p><pre>def logEachBad[T, F[_]](ft: F[T])<br>                       : MessageGen[T] =&gt; Logger =&gt; F[T] = {<br>                         msgGen        =&gt; logger =&gt;<br>    ft.<strong>foreach</strong>(t =&gt; <em>log</em>(t)(msgGen)(logger))<br>    ft<br>  }</pre><p>but this won’t compile because there is no evidence that F[T] has a foreach function.</p><h4>Generalising ForEach using Type Classes</h4><p>This is interesting because Option, List etc. <em>do</em> have foreach functions. The problem is that there is no trait that these types have in common with Future that we can use as a type bound to F[_] to prove that.</p><p>But we can make one:</p><pre>trait ForEach[T, F[_]] {<br>  def forEach(ft: F[T]): (T =&gt; Unit) =&gt; Unit<br>}</pre><p>ForEach⁵ is a <a href="https://books.underscore.io/essential-scala/essential-scala.html#sec:type-classes">type class</a> that we will use to provide F[_] with forEach⁶ functionality for List, Future, Option etc.</p><p>The implementations are trivial and make use of <a href="https://www.waitingforcode.com/scala-core/java-sam-scala/read">SAM conversion</a>⁷, allowing us to implement the single abstract method of the ForEach trait with a lambda:</p><pre>implicit def optionForEach[T]: ForEach[T, Option] =<br>  (t: Option[T]) =&gt; t.foreach</pre><p>The implementation for List, Set, Option et al. would, in fact, all be identical, because <em>they</em> share a common trait — <a href="https://www.scala-lang.org/api/current/scala/collection/IterableOnce.html">IterableOnce</a> — which contains their foreach method. So we can replace the above with:</p><pre>implicit def itrForEach[T, F[A] &lt;: IterableOnce[A]]: ForEach[T, F] =<br>  (ft: F[T]) =&gt; ft.iterator.foreach</pre><p>Which lets us cover List, Set, Option and all other IterableOnce subclasses.</p><p>This, combined with the implementation for Future:</p><pre>implicit def futureForEach[T](implicit ec: ExecutionContext)<br>                             : ForEach[T, Future] =<br>  (ft: Future[T]) =&gt; ft.foreach</pre><p><em>should</em> cover most cases.</p><p>Each implementation is tagged as implicit. We can see why when we look at the updated definition for logEach:</p><pre>def logEach[T, F[_]](ft: F[T])<br>                    <strong>(implicit fe: ForEach[T, F])</strong><br>                    : MessageGen[T] =&gt; Logger =&gt; F[T] =<br>                      msgGen        =&gt; logFn  =&gt; {<br>  fe.forEach(ft)(t =&gt; <em>log</em>(t)(msgGen)(logFn))<br>  ft<br>}</pre><p>When a client wants to log a Future, the implicitForEach value must be available in <a href="http://eed3si9n.com/implicit-parameter-precedence-again/">implicit scope</a>. The compiler will then provide it as the ForEach[T, F] parameter.</p><p>This is <a href="https://medium.com/analytics-vidhya/type-classes-for-ad-hoc-polymorphism-in-scala-70ec31d0265d">ad-hoc polymorphism</a> and it’s awesome!</p><p>We can ensure all instances are in implicit scope by putting them in ForEach’s <a href="https://docs.scala-lang.org/overviews/scala-book/companion-objects.html">companion object</a>⁸:</p><pre><strong>object ForEach</strong> {<br>  implicit def futureForEach ...<br>}</pre><p>Then, simply importing ForEach itself brings all of the implicit instances into scope:</p><pre><strong>import util.ForEach</strong><em><br><br></em>val <em>intF</em>: Future[Int] = <em>calculateFancyInt</em>()<br>val <em>msgGenInt: MessageGen[Int] </em>= { case 0 =&gt; &quot;Zero returned!&quot; }<br><em>logEach</em>(<em>intF</em>).using(<em>msgGenInt</em>).atLevel(<em>info</em>).andReturn</pre><p>Observe that in logEach, the type of the MessageGenerator — T and the return type of logEach — F[T] are different, unlike log in which they are the same.</p><p>This means we have to make a small change to one of our earlier implicit classes to accommodate that:</p><pre>implicit class MessageGenOps2<strong>[T, R]</strong><br>  (f: MessageGen[T] =&gt; Logger =&gt; <strong>R</strong>) {<br>    def using(msgGen: MessageGen[T]): Logger =&gt; <strong>R</strong> = f(msgGen)<br>}</pre><h4>One more thing - Either</h4><p>As its name suggests, the value of an <a href="https://www.scala-lang.org/api/current/scala/util/Either.html">Either[A, B]</a>can be either Left(a: A) or Right(b: B).</p><p>It has a foreach method that is a bit like Option’s in that if the Either is a Right(b), it will provide that value to the supplied procedure, but if it’s a Left, it will not call the procedure at all.</p><p>The problem is that its type constructor takes <strong>two</strong> type parameters, so it doesn’t fit the patternForEach[T, <strong>F[_]</strong>]which expects just one.</p><p>We can solve that by fixing the A parameter⁹ to, for example, Error:</p><p>type ErrorOrT[T] = Either[Error, T]</p><p>Then:</p><pre>implicit def errorOrTForEach[T]: ForEach[T, ErrorOrT] =<br>  (ft: ErrorOrT[T]) =&gt; ft.foreach</pre><p>We can use a similar trick to let us log a nested type¹⁰ using the inner value, for example:</p><pre><strong>type FutureOption[T] = Future[Option[T]]</strong><br>implicit def futureOptionForEach[T](implicit ec: ExecutionContext)<br>                                   : ForEach[T, FutureOption] =<br>  (ft:   FutureOption[T]) =&gt; <br>  (proc: T =&gt; Unit)       =&gt; ft.foreach(opt =&gt; opt.foreach(proc))</pre><p>This will let us log a Future[Option[T]] using a MessageGen[T]¹¹</p><h4>Conclusions</h4><p>Logging is important. Your on-call support team will thank you for it if it’s done well (and curse you if it’s not).</p><p>The small <a href="https://en.wikipedia.org/wiki/Domain-specific_language">DSL</a> presented here is designed to make it easy to log messages in a way that is clear for the reader of the code and all without adding unsightly postscripts to your functions.</p><p>So, no excuses!</p><p>¹ The aesthetics of code are, of course, purely subjective.</p><p>² We define a procedure as any function that returns Unit.</p><p>³ We are using <a href="https://www.playframework.com/documentation/2.8.x/api/scala/play/api/Logger.html">play.api.Logger</a> here, which uses <a href="https://www.slf4j.org/">slf4j</a> under the covers.</p><p>⁴ This is <a href="https://medium.com/@scelestino/polymorphism-in-scala-part-1-34015f9b5b13">parametric polymorphism</a>.</p><p>⁵ ForEach is slightly more constrained than the foreach methods of Future, Option etc. They expect a function of T =&gt; U where we require T =&gt; Unit. In practice, the reason that the type variable is called U is that it will be discarded even if it is not Unit, so you <em>could</em> pass a function of, say, T =&gt; String to foreach, but you’ll never know what the String value was.</p><p>⁶ I’ve never understood why foreach is all one case in Scala libraries.</p><p>⁷ The T parameter in ForEach could have been brought down to the function level, but <a href="https://www.scala-lang.org/files/archive/spec/2.12/06-expressions.html#sam-conversion">SAM Conversion would not then be possible</a> as the single abstract function would be polymorphic.</p><p>⁸ The alternative would be to put them either in the same or separate objects and import them individually as needed. In cases where the implicits might be ambiguous, this would be required.</p><p>⁹ Or we could have used a <a href="https://github.com/typelevel/kind-projector">kind projector</a>.</p><p>¹⁰ Future[Option[T]] is not a higher kinded type since Future is defined as Future[T]not Future[F[_]], it just happens that T is being bound to a generic type in this case.</p><p>¹¹ We could have used a monad transformer like <a href="https://typelevel.org/cats/">Cats</a>’ <a href="https://typelevel.org/cats/api/cats/data/OptionT.html">OptionT</a> here to simplify this implementation, but since I got all the way through this article without mentioning the M word, I didn’t want to spoil it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=342627ad72ba" width="1" height="1" alt=""><hr><p><a href="https://engineering.depop.com/clear-and-concise-logging-in-scala-342627ad72ba">Clear and concise logging in Scala.</a> was originally published in <a href="https://engineering.depop.com/">Engineering at Depop</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Depop]]></title>
            <link>https://engineering.depop.com/monitoring-depop-d5331573b13e?source=rss-dacaf5d97315------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5331573b13e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Jon Humble]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 17:11:02 GMT</pubDate>
            <atom:updated>2021-11-02T17:11:02.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOjc-R4elLXkKiQ9QAh4Tg.jpeg" /><figcaption><a href="https://www.flickr.com/photos/21186555@N07/25030167161">“Palawan Water Monitor Lizard on The Beach”</a> by <a href="https://www.flickr.com/photos/21186555@N07">Ray in Manila</a> is licensed under <a href="https://creativecommons.org/licenses/by/2.0/?ref=ccsearch&amp;atype=rich">CC BY 2.0</a></figcaption></figure><p>At <a href="https://www.depop.com/">Depop</a> we care passionately about our users’ experience of our marketplace. We want it to be <em>the</em> place to go for sellers and buyers alike.</p><p>So we carefully monitor our software to ensure we are providing the best service we can. That way, users can focus on buying and selling, while our software can be the invisible enabler.</p><h3>We’ve all been here</h3><p>As engineers at Depop, we’re on the, “other side” — providing services instead of consuming them.</p><p>Of course we’re also consumers of software services too (and Depop!), so we’ve experienced frustrations like:</p><ul><li>Searches that get, “stuck” and never seem to return;</li><li>Payments that hang and leave us wondering if the money was sent or not;</li><li>Sites that crash when you’re trying to buy tickets for a popular event.</li></ul><h3>Categorising User Pain Points</h3><p>We can generalise the specific pain points above into:</p><ul><li>Slow responses</li><li>Errors</li><li>Availability</li></ul><p>This is where monitoring comes in. We ingest all of our telemetry data into <a href="https://www.datadoghq.com/">DataDog</a> using <a href="https://kamon.io/telemetry/">Kamon</a>.</p><p>DataDog then carefully watches for symptoms of problems using monitors we have defined to match our requirements.</p><h3>We don’t control it all</h3><p>Alas, we don’t control everything, for example:</p><ul><li>We might use a third party services like <a href="https://www.paypal.com/uk/home">PayPal</a>;</li><li>The network between a user’s phone and our servers might be 4G from a telco.</li></ul><p>However, these two examples are <em>not</em> equal. We must take responsibility for the service of our contracted third parties, so we monitor <em>their</em> service closely and ensure it meets our users’ requirements and the provider’s <a href="https://en.wikipedia.org/wiki/Service-level_agreement">SLA</a>.</p><p>On the other hand, the network connection to our servers is completely out of our hands and we can neither monitor nor enforce standards onto it. Pick your network provider wisely!</p><h3>Controlling the controllables</h3><p>That said, most things are in our control and so we take care to monitor both first and third party:</p><ul><li>Latency — looking for slow responses;</li><li>Error rates — looking for failures;</li><li>Throughput — looking for signs of an outage.</li></ul><h3>Raising the alarm</h3><p>It’s no good monitoring if no-one knows when the monitoring has spotted something important! So, anomalous observations are immediately posted to the relevant team’s <a href="https://slack.com/intl/en-gb/">Slack</a> channel for their investigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*MXSZFGVixXzxoQ0_.png" /><figcaption>A throughput anomaly.</figcaption></figure><p>That approach works well during working hours, but what about at night? Thankfully, our dedicated Depop engineering team is on call 24/7 and an engineer will be paged when an alert occurs — <a href="https://www.pagerduty.com/">PagerDuty</a> is always awake!</p><h3>Defining bad</h3><p>So, what is slow? What is too many errors? What is low throughput?</p><p>These are the sorts of things where you know it when you see it, but it’s hard to put a specific number on it.</p><p>Still, hard is what we engineers are here for, so we make some choices:</p><ul><li>We monitor calls at the HTTP API level, which gives us the closest value we can get to the client experience — this is the yellow box in the diagram, below.</li><li>We monitor each API endpoint separately to give us the granularity we need for the investigation of anomalies.</li><li>We sample the calls over a window of five minutes and average them out, to prevent single wayward readings triggering alarms.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FLDaGSIRFKsKJCDtO5UUg.png" /><figcaption>Figure 1: We monitor calls at the HTTP API level (yellow) and third party (pink).</figcaption></figure><p>Finally, we define some thresholds:</p><ul><li>If calls from our clients to our API take more than 400ms, they’re slow.</li><li>If an endpoint on our API fails more than 1% of the time, it’s error prone.</li><li>If the throughput of an API is 3 standard deviations below where it normally is at this time of day, we have a throughput issue.</li></ul><h3>Exceptions</h3><p>Monitoring is only useful if it tells you when things are awry. If alarms sound frequently for things that are not problems, or are conditions that are expected, then the useful monitoring gets drowned in noise.</p><p>For this reason, there are exceptions to our rules.</p><h4>Low throughput endpoints</h4><p>Some endpoints have greater throughput than others and all vary during the day. This means that there are times when some endpoints do not generate enough samples in a five minute window to give a reliable reading.</p><p>We look to get <em>at least</em> ten readings from an endpoint in its time window. If this is not possible at the lowest throughput of the day, we make the window wider. So we may end up with ten, thirty, sixty or even one hundred and twenty minute windows.</p><p>The trade-off here is between reliability and timeliness. With a wider window, it will take longer to know if there is a problem, but it’s more likely to be a genuine problem.</p><h4>Calls to third parties</h4><p>Endpoints whose implementation involves calling out to a third party are a special case. That extra HTTP call out to the internet adds latency and the third party will have its own <a href="https://en.wikipedia.org/wiki/Service-level_objective">SLOs</a> within their SLA with Depop.</p><p>We monitor third parties at the client layer (See the pink box in figure 1, above) and check their error and latency rates against their SLOs.</p><p>We also adjust out monitoring at the endpoint layer to take into account third party SLOs.</p><h3>While you’ve been here</h3><p>We’ve been monitoring — and we still are. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5331573b13e" width="1" height="1" alt=""><hr><p><a href="https://engineering.depop.com/monitoring-depop-d5331573b13e">Monitoring Depop</a> was originally published in <a href="https://engineering.depop.com/">Engineering at Depop</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Content Negotiation in HTTP]]></title>
            <link>https://engineering.depop.com/content-negotiation-in-http-ab763ddbc147?source=rss-dacaf5d97315------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab763ddbc147</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jon Humble]]></dc:creator>
            <pubDate>Wed, 30 Jun 2021 16:30:40 GMT</pubDate>
            <atom:updated>2021-06-30T16:30:40.945Z</atom:updated>
            <content:encoded><![CDATA[<p>Content negotiation is defined as:</p><p><em>The process of selecting the best representation for a given resource when there are multiple representations</em> <em>available</em>.</p><p>This article examines why this is useful and how it can be done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e3DbudK1OlzI-IEqb9gK_Q.jpeg" /><figcaption><a href="https://www.flickr.com/photos/18090920@N07/12696323254">“fruit”</a> by <a href="https://www.flickr.com/photos/18090920@N07">Sean MacEntee</a> is licensed under <a href="https://creativecommons.org/licenses/by/2.0/?ref=ccsearch&amp;atype=rich">CC BY 2.0</a></figcaption></figure><h3>Resources and Representations</h3><p>We’ll start with some definitions.</p><p>Let’s say I have a printer on my desk in <a href="https://www.depop.com/">Depop</a>’s palatial Manchester offices¹. The printer itself is a <strong>resource</strong>, that we wish to make available on the network.</p><p>We don’t actually send <em>the printer</em> over the network of course! Instead, we send a <strong>representation</strong> — some snapshot of the printer’s state.</p><p>It might look something like this:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;status&quot;: &quot;online&quot;, <br>    &quot;description&quot;: &quot;The printer on Jon&#39;s desk&quot;,<br>    &quot;ink&quot;: 56,<br>    &quot;paper&quot;: true,<br>    &quot;url&quot;: &quot;https://depop.com/printers/man/4&quot;<br>  }<br>}</pre><p>This is a JSON representation of some data about the printer.</p><p>An alternative representation could look like this:</p><pre>data:<br>  status: online<br>  description: The printer on Jon&#39;s desk<br>  ink: 56<br>  paper: true<br>  url: <a href="https://depop.com/printers/man/4">https://depop.com/printers/man/4</a></pre><p>This is a YAML representation of the data. This is a variation in <strong>content-type</strong>. Here’s more YAML:</p><pre>data:<br>  status: онлайн<br>  description: Принтер на столі Джона<br>  ink: 56<br>  paper: true<br>  url: <a href="https://depop.com/printers/man/4">https://depop.com/printers/man/4</a></pre><p>This time the document string values have been translated — this is the Ukrainian version. The representation has varied in its (human) <strong>language</strong>.</p><p>The act of asking for and providing alternative representations is what content negotiation is all about.</p><h3>What can vary?</h3><p>HTTP has built in support for specifying preferences using these headers:</p><p>Accept — representation format — e.g. XML, JSON etc.</p><p>Accept-Language — representation language — English, Spanish, Russian etc.</p><p>Accept-Encoding — representation encoding — <a href="http://www.gzip.org/">gzip</a>, <a href="https://en.wikipedia.org/wiki/Brotli">br</a> etc.</p><p>There also used to be a Accept-Charset header, but it is now deprecated².</p><h3>How does negotiation occur?</h3><p>The specification for negotiation can be found in <a href="https://datatracker.ietf.org/doc/html/rfc7231#section-3.4">Section 3.4 of RFC 7231</a> — there are two basic flavours, server or agent (client) driven.</p><p>In the case of server-driven negotiation, the client specifies its requirements in headers and the server runs an algorithm to select the best representation.</p><p>Conversely, in client-driven negotiation it is the client who runs an algorithm to decide which representation to use from a selection provided by the server.</p><p>Let’s take a more in depth look at both³.</p><h3>Server-Driven Negotiation</h3><h4>Specifying Requirements</h4><p>Here are some example headers a client may specify:</p><pre>Accept: application/json<br>Accept-Language: es-mx<br>Accept-Encoding: gzip</pre><p>This client is requesting a JSON response in Mexican Spanish compressed using the GZIP algorithm.</p><h4>Lo siento, no hablamos español</h4><p>Alas, the printer on my desk does not speak Spanish, so what can the server do?</p><ul><li>Return 406 Not Acceptable</li><li>Return a default document, e.g. unzipped, in English etc.</li></ul><p>The former is perhaps <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/406">more correct</a> but the latter is more likely. Neither are desirable so what could the client have done?</p><h4>Preferences, not demands</h4><p>Instead of hard and fast demands, the client can give preferences, like this:</p><pre>Accept: application/json, application/xml;q=0.9<br>Accept-Language: es-mx, es;q=0.9; en;q=0.8, *;q=0.7<br>Accept-Encoding: gzip, identity;q=0.9 </pre><p>The comma separated values for each header specify preferences and the q values represent weightings (no weighting means q=1.0, the most desirable option).</p><p>Taking the Accept-Languageheader above as an example, we can read it like this:</p><p><em>I’d prefer Mexican Spanish, but any form of Spanish will do; if you’d don’t have Spanish then English is acceptable and if you don’t have that either then just send me what you </em><strong><em>do</em></strong><em> have.</em></p><p>This is a much more flexible approach and as it happens, my printer endpoint can satisfy all these requirements by sending JSON in English with GZIP compression.</p><h4>Limitations</h4><p>The client can only really specify the three standard headers⁴ listed above in order to get the representation it wants. The client and server could have an agreement that the header X-Funky-Header has some semantics to help choose a representation, but that would be an <em>out of band</em>⁵ agreement and so it is not recommended.</p><h3>Client-Driven Negotiation</h3><p>If having the server decide which representation to use is too limiting for a particular use-case, the alternative is to reverse the roles and have the client decide based on information from the server.</p><p>In this case, when a client requests a resource with multiple representations, the server responds with:</p><pre>300 Multiple Options</pre><p>and a payload describing the options with unique links to each.</p><p>The client then simply chooses the one it wants and follows the link to get it.</p><h4>Not so simple</h4><p>Alas, it’s not quite so easy. There is no agreed format for the payload response and therefore no obvious algorithm for the client to use to choose the representation it wants.</p><h4>Cache in hand</h4><p>On top of that, some of you are probably thinking, “That means we have to make two requests to get that resource.”</p><p>Not to worry! Both requests can and should be cached⁶, so the cost is minimal and if you need this flexibility, it is more than worth it.</p><h4>How to do it</h4><p>Presuming the client and server are using a hypertext aware content-type to communicate⁷, it makes sense to use this to describe the options to the client. To ensure this, the client can add a header to that end, e.g.:</p><pre>Accept: application/vnd.api+json</pre><p>Now we need a document in that format that describes the ways the representation can vary, with links to each variation:</p><pre>{<br>  &quot;links&quot;: {<br>    &quot;option 1&quot;: {<br>      &quot;meta&quot;: {<br>        &quot;supports&quot;: &quot;Draft-07&quot;,<br>        &quot;lang&quot;: &quot;en-gb&quot;<br>      },<br>      &quot;href&quot;: &quot;/api/address/schemata/address/1&quot;,<br>      &quot;type&quot;: &quot;application/schema+json&quot;<br>    }<br>    &quot;option 2&quot;: {<br>      &quot;meta&quot;: {<br>        &quot;supports&quot;: &quot;2020-12&quot;,<br>        &quot;lang&quot;: &quot;en-gb&quot;<br>      },<br>      &quot;href&quot;: &quot;/api/address/schemata/address/2&quot;,<br>      &quot;type&quot;: &quot;application/schema+json&quot;<br>    }</pre><pre>  }</pre><pre>}</pre><p>The nice thing about this method is we have more freedom over the aspects a representation can vary in. In this case, we are using knowledge of the support for different versions of JSON Schema⁸.</p><p>¹ Full disclosure — I have never been to the office. It may or may not be palatial. Or a bike shed.</p><p>² The widespread adoption of UTF-8 means that we rarely need such functionality these days. See <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset">this article</a> on MDN.</p><p>³ There’s also some good covergae on MDN <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation">here</a>.</p><p>⁴ <a href="https://www.rfc-editor.org/rfc/rfc8942.html">RFC 8942</a> floats an idea about Client Hints that could extend this.</p><p>⁵ There’s a good description of OOB in <a href="https://stackoverflow.com/a/4965160">this Stack Overflow thread</a>.</p><p>⁶ Lots more about caching in another <a href="https://engineering.depop.com/caching-in-web-apis-ff43fd7e893">article</a> on this blog by yours truly.</p><p>⁷ Which you really should be! I talk more about hypermedia in <a href="https://engineering.depop.com/using-hypermedia-in-web-apis-15d4258951c4">this blog post</a>.</p><p>⁸ Although this is an illustrative example, profiles are often a better way to do this if the MIME type in question supports them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab763ddbc147" width="1" height="1" alt=""><hr><p><a href="https://engineering.depop.com/content-negotiation-in-http-ab763ddbc147">Content Negotiation in HTTP</a> was originally published in <a href="https://engineering.depop.com/">Engineering at Depop</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching in Web APIs]]></title>
            <link>https://engineering.depop.com/caching-in-web-apis-ff43fd7e893?source=rss-dacaf5d97315------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff43fd7e893</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[http-caching]]></category>
            <dc:creator><![CDATA[Jon Humble]]></dc:creator>
            <pubDate>Fri, 23 Apr 2021 08:40:14 GMT</pubDate>
            <atom:updated>2021-04-23T09:03:06.501Z</atom:updated>
            <content:encoded><![CDATA[<p><em>There are only two hard things in Computer Science: cache invalidation and naming things.</em></p><p><em>— Phil Karlton</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y_VW-49QLuCzFQnDSOE1wQ.jpeg" /><figcaption><a href="https://www.flickr.com/photos/8718930@N07/3462606643">“Server room at CERN”</a> by <a href="https://www.flickr.com/photos/8718930@N07">torkildr</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/2.0/?ref=ccsearch&amp;atype=rich">CC BY-SA 2.0</a></figcaption></figure><p>It’s clear from its name that the World Wide Web scales well. One of the reasons for this is HTTP caches. At Depop we want to make sure we maximize the benefits of this technology for our users.</p><p>Getting caching right is notoriously difficult, so here’s an overview of the options and ideas on how to get the best out of them.</p><h4>Types of cache</h4><p>We will differentiate between two types of cache:</p><p><strong>Local caches</strong> reside on the same device as the user agent — typically a mobile phone or computer. They store responses <em>privately</em>, just for the user of the device.</p><p><strong>Shared caches</strong> on the other hand are found somewhere on the network between the user’s device and the origin server. Indeed, there may be several of these along the way. They store many users’ responses and these responses can be used to satisfy requests from other users if the requests are the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCmxsRXn6QWt_NZrCleGkg.png" /><figcaption>Figure 1: A simple view of how caches may look between a Depop user and our servers.</figcaption></figure><p>Local caches are the closest to the user, so will result in the least latency. However, they are less likely to have responses cached as they see only the responses for a single user. Shared caches on the other hand may have a response cached from another user that this user can use, so are more likely to result in a cache hit.</p><h4>The benefits of caching</h4><ul><li><strong>Reduced Latency</strong>: The client will receive a cached response quicker than if the request had to go to the origin server. This is because the cache is closer to the client on the network and it does not have to do any processing.</li><li><strong>Reduced Server Load</strong>: Any response served by the cache saves the server having to do any work to service the request.</li><li><strong>Reduced Network Load</strong>: Any response served by the cache means the network between the cache and the origin server is not utilized.</li></ul><h4>What’s the cost?</h4><p>All these benefits have to come with a cost and with caching the cost is consistency. The more aggressively we take advantage of caching, the more likely it is we will serve the client a stale response. We will look at how to balance these concerns shortly.</p><h4>What gets cached?</h4><p>For our purposes, we will focus on GET requests resulting in 200 responses. <a href="https://httpwg.org/specs/rfc7234.html">RFC 7234</a> covers HTTP caching and section 2 has some notes on other, less common, caching scenarios.</p><p>It’s worth noting that to a client, a cache looks like it <em>is</em> the origin server. A client does not distinguish between a response from the origin server and one from any cache on the way¹.</p><h4>Configuring how responses get cached</h4><p>Caching is configured by headers in the responses from the origin server.² There are three main factors that can be controlled — cache selection, cached item freshness and cached item validation.</p><p><strong>Cache Selection</strong></p><p>Cache selection covers <em>where</em> the response can be cached.</p><p>If the item must not be cached anywhere, we use the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control">cache-control</a> directive thus²:</p><p>cache-control: no-store</p><p>To allow only local caches to cache a response, we use :</p><p>cache-control: private</p><p>Shared caches should respect this and not store any such decorated response.</p><p>Finally, we can use:</p><p>cache-control: public</p><p>to allow all caches to store the response. This is the usually the default, but there are circumstances involving authenticated requests in which we may need to use it, as we will see later.</p><p><strong>Freshness</strong></p><p>Caches are allowed to serve cached responses to clients so long as the cached item remains <em>fresh</em>. What is considered fresh is determined by the response headers³ outlined below:</p><pre>expires: Wed, 21 Oct 2020 00:00:00 GMT</pre><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expires">expires</a> header sets an absolute point in time before which a response is considered fresh.</p><pre>cache-control: max-age=600</pre><p>The max-age and s-maxage settings set a relative amount of time, in seconds, that the response is considered fresh relative to its original generation time on the origin server. The latter applies to shared caches only and overrides the former which applies to both types of cache.</p><p><strong>Validation</strong></p><p>When a cached response is requested, but found to be stale, the cache will, by default, reach out to the origin server for a fresh copy⁴, which it will then store and serve to the client.</p><p>However, HTTP has a better mechanism — a means to re-validate the freshness of the item without having to make the full request/response cycle.</p><p>This mechanism is known as a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests"><em>conditional GET</em></a> and depends upon the presence of a <em>validator </em>in the response. A validator is one of these headers:</p><p>last-updated: Wed, 21 Oct 2020 10:19:02 GMT</p><p>etag: 345312-af5445-eaf43-12eec</p><p>The former header conveys the time the response was last updated. When such a response expires, the cache can issue a conditional GET using the request header:</p><p>if-modified-since: Wed, 21 Oct 2020 10:19:02 GMT</p><p>If the response has not been updated, the server will respond with 304 Not Modified and the cache can serve the cached item to the client and refresh the freshness value it has for this response.</p><p>If the response has been updated, the server will respond with a typical 200 response and a new response will be sent. This replaces the old one in the cache and is then served to the client.</p><p>Entity Tags (etag) work in a similar manner, but have the advantage that they can change more often than every second. The conditional header for etags is if-none-match: 345312-af5445-eaf43-12eec</p><p>All of this is transparent to the original calling client — the conditional GET headers are only put on requests from the cache by the cache.</p><p><strong>Invalidation</strong></p><p>When a cache sees a request using one of the unsafe verbs (DELETE, PUT, POST), it must <a href="https://httpwg.org/specs/rfc7234.html#invalidation">remove any item from its cache</a> that matches the URI associated with this request.</p><p>Similarly, it must also invalidate any cached item that matches the location or content-location headers in the responses to these requests.</p><p>Sadly, in practice this can be a slow and unreliable process (Some CDNs can take 20 minutes or so to reach global consistency). For this reason, it’s best not to rely on this form of invalidation as a means of cache management. This puts more onus on the correct choice of caching freshness parameters.</p><h4>Trade Offs</h4><p><strong>Favouring Consistency</strong></p><p>For the ultimate consistency, caching can be switched off altogether using the no-store directive¹. However, there is a better mechanism.</p><p>Provided the response contains a validator, the cache can be directed to revalidate every request. This uses a conditional GET rather than a full get and should reduce bandwidth and server utilisation:</p><p>cache-control: no-cache, public, must-revalidate</p><p>The no-cache directive¹ often confuses — it means that the cache can <em>store</em> the response, but not <em>serve</em> it without first checking with the origin server.</p><p><strong>Favouring Low Latency (also favours low network and server load)</strong></p><p>Low latency is best achieved by getting the most cache hits. To achieve this, we can use a relative or absolute cache expiry time, e.g.</p><pre>cache-control: max-age=3600</pre><p>Increasing the value of max-age will improve latency at the possible expense of consistency.</p><p>Once the cached item expires, the cache will make a call to the origin server for a fresh copy.</p><p>We can improve this by adding a validator to the response, e.g.</p><pre>etag: ae91-bb6c-9632-00d0</pre><p>Now, the cache makes a <em>conditional</em> GET when the cached response expires, potentially saving bandwidth and server resources.</p><p>This will be done at the time a request comes into the cache for the resource in question, blocking that request while it does so. We can improve this by specifying <em>background </em>updating of the items in the cache thus:</p><pre>cache-control: stale-while-revalidate=1800</pre><p>With this directive in place, if a request comes in for the cached response within 1800s of it expiring in the cache, the currently caches response will be served to the client while a revalidate request is made to the origin server. Hence the cache will be refreshed when the next request comes in.</p><p>By balancing the values for max-age and stale-while-revalidate we can achieve background updating of resources while minimising latency.</p><p><strong>Maximising Resilience</strong></p><p>Caches also come in useful if the origin server suffers an outage. In these circumstances, a cache can be directed to continue to serve stale responses for a period while the origin server is returning errors:</p><pre>cache-control: stale-if-error=3600</pre><p>In this example, were the origin server to go down for an hour, the cache would continue to serve clients with cached responses <em>even if</em> they had gone stale.</p><h4>Security Considerations</h4><p>Encrypted data over SSL is not cacheable. The random jumble of bits resulting from encryption are different every time and only the original sender and recipient have the keys.</p><p>Responses from requests with authorisation are not cached by default for security reasons.</p><p>Together, these facts would seem to be bad news for caching!</p><p>There are, thankfully, things we can do.</p><p>Remember this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCmxsRXn6QWt_NZrCleGkg.png" /></figure><p>SSL termination may happen before the origin server, giving a space for unencrypted data to be cached. In the diagram above, that might mean the ISP cache cannot be used, but the CDN one can.</p><p>With authorised content, we can enable caching, but must do so with caution.</p><p>One option is private caching:</p><pre>cache-control: private, max-age=600</pre><p>Here, we enable caching on the user’s device only.</p><p>An alternative is public caching with forced validation:</p><pre>cache-control: public, max-age=0, must-revalidate</pre><p>This allows the cache to store the item, but forces it to do a conditional GET to the origin server. This GET must pass AUTH or it will result in a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401">401</a>. This ensures the client is allowed to view the cached content without having to re-generate it each time.</p><p>For this to work effectively, the response will also have to have a validator in it — e.g. an etag or a last-modified.</p><h4>Deciding how to cache resources</h4><p>A cache represents a trade-off between latency and consistency. The more risk you take over consistency, the better your latency. Here are some things to consider when setting up the caching for your resources:</p><p><strong>Volatility</strong> — how likely is the resource to go stale in time period X? This helps with choosing a freshness period.</p><p><strong>Frequency</strong> — how often is the resource accessed? This points to the cost of having cache misses and having to engage the origin server.</p><p><strong>Security</strong> — are we happy to have this in a shared cache in a publicly accessible part of the network? Or should it only be cached privately? Or not at all?</p><h4>URI to Resource uniqueness</h4><p>Shared caches depend on URIs uniquely identifying resources⁵. If a different resource is returned for the same URI based on another variable (often the calling user), caching won’t work!</p><p>Don’t get carried away with server side optimisations. Let the caches take the load.</p><h4>In Conclusion</h4><p>Caching is an imperfect science. Getting it right requires monitoring your cache hit rates and watching out for stale data being served. Hopefully this article has given you some ideas and pointers to get the most out of this important technology.</p><p>¹ Caches add specific headers to responses, so if you look carefully you can tell if a response came from a cache.</p><p>² Not all cache implementations respect this directive. In particular Varnish pre-version 4.</p><p>³ Clients can also put headers in their requests to modify these settings.</p><p>⁴ If responses do not contain freshness directives, caches can use heuristics to decide on freshness.</p><p>⁵If another cache en route to the origin server has a fresh copy, that can be used instead.</p><p>⁶ Multiple URIs can point to the same resource, but a single URI must only ever point to one resource.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff43fd7e893" width="1" height="1" alt=""><hr><p><a href="https://engineering.depop.com/caching-in-web-apis-ff43fd7e893">Caching in Web APIs</a> was originally published in <a href="https://engineering.depop.com/">Engineering at Depop</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Hypermedia in Web APIs]]></title>
            <link>https://engineering.depop.com/using-hypermedia-in-web-apis-15d4258951c4?source=rss-dacaf5d97315------2</link>
            <guid isPermaLink="false">https://medium.com/p/15d4258951c4</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Jon Humble]]></dc:creator>
            <pubDate>Fri, 26 Feb 2021 14:25:07 GMT</pubDate>
            <atom:updated>2021-02-26T21:31:28.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oS_WyrTSGdEDFVVRWFxMbQ.jpeg" /></figure><p>Like many companies, <a href="https://www.depop.com/">Depop</a> makes significant use of Web APIs. Given the ubiquity of them within our company, we’re keen to ensure we get the best out of them.</p><p>Now, hypermedia is something we’re all familiar with. You’re looking at it now — this page is hypertext — text with embedded <a href="https://www.depop.com/">links</a> that can take you to more text. Wonderful.</p><p>So why is it that so often our Web APIs ignore this technology? Sure, we might use HTTP to GET, PUT and POST our entities, which gets us out of <a href="https://www.martinfowler.com/articles/richardsonMaturityModel.html">the swamp of POX</a>, but it still leaves us with problems. Problems we can often solve via the magic of links.</p><h3>What Problems?</h3><p>A typical CRUD based Web API acts like a database over HTTP. Instead of SELECT, INSERT and DELETE we have GET, POST and DELETE and the rest is largely data munging.</p><p>Say we tell our clients that we have a resource, e.g. an address.</p><p>They can GET the addresses for a user like this:</p><pre>https://www.depop.com/addresses/{user_id}</pre><p>All they have to do is fill out the missing <a href="https://tools.ietf.org/html/rfc6570">URI parameter</a>.</p><p>To add a new address for the user, they can POST there too.</p><p>To edit or delete they have to know the specific address ID, then they can PUT, DELETE or GET to:</p><pre>https://www.depop.com/addresses/42ab-89cf/{address_id}</pre><p>Just fill in the blanks.</p><p>But you see, this is a bit like your favourite news site listing headlines, then making you edit the URL in the location bar to get to the story. Who would put up with that?</p><p>On top of this:</p><ul><li>The clients have to know the IDs.</li><li>The clients have to know the <a href="https://tools.ietf.org/html/rfc6570">URI templates</a>.</li></ul><p>Passing around IDs is not so great, especially if they’re your actual database IDs. Sharing all those URI templates is even worse — it makes for <em>strong coupling</em> between client and server. Every template known to the client becomes part of your API and <strong>you cannot change them</strong> on the server side — ever — without breaking old clients.</p><p>Which is why we end up with URIs like this:</p><pre>https://www.depop.com/example/v1/addresses/{user_id}<br>https://www.depop.com/example/v2/addresses/{user_id}<br>https://www.depop.com/example/v3/addresses/{user_id}</pre><p>to enable us to evolve our API without breaking old clients. Maintenance nightmare, especially if you change your APIs often!</p><p>But there is a better way.</p><h3>Hypermedia</h3><p>Before we look at hypermedia solutions, we need to talk about JSON, by which I mean <a href="https://tools.ietf.org/html/rfc8259">application/json</a>.</p><p>Here’s some example JSON:</p><pre>{ <br>  &quot;addresses&quot;: [ <br>    &quot;https://www.depop.com/example/addresses/e5f1-119a/1&quot;,<br>    &quot;https://www.depop.com/example/addresses/e5f1-119a/3&quot;,<br>    &quot;https://www.depop.com/example/addresses/e5f1-119a/7&quot;<br>  ]<br>}</pre><p>Just a simple object with a list of links inside it.</p><p>Except it’s not.</p><p>The JSON <a href="https://tools.ietf.org/html/rfc8259">specification</a> defines six basic types, <em>none of which are links</em>. The above items are <strong>strings</strong>.</p><p>Now, we could try parsing every string value in a JSON document looking for “http” but it wouldn’t get us far, especially when it comes to <a href="https://www.w3schools.com/Html/html_filepaths.asp">relative links</a>.</p><p>We need something better.</p><p>HTML <em>does</em> have links. When you see:</p><pre>&lt;a href=”<a href="http://www.depop.com/example/addresses/e5f1-119a/1">https://www.depop.com/example/addresses/e5f1-119a/1</a>”&gt;<br>  My First Address<br>&lt;/a&gt;</pre><p>You know that’s a link. The semantics of HTML <a href="https://tools.ietf.org/html/rfc1866#page-36">say so</a>.</p><p>Sadly, HTML does not make for a client friendly payload in our APIs. However, it turns out that there are lots of <a href="https://github.com/kevinswiber/siren">flavours</a> <a href="http://stateless.co/hal_specification.html">of</a> <a href="http://amundsen.com/media-types/collection/">JSON</a> with hyperlink semantics baked in. The one we have chosen to focus on is <a href="https://jsonapi.org/">JSON:API</a>.</p><h3>Loosening the coupling</h3><p>The key to loosening the coupling is for the server to <em>provide links</em> in the response body to the client. The client can then follow those links without having to know anything about composing URIs with IDs. Let’s look at an example¹ of a user’s address book:</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;id&quot;: &quot;e1fc-0f9d&quot;,<br>      &quot;attributes&quot;: { <br>        &quot;display”: &quot;12 Spalding Road, Harrogate, HG1 4SF&quot;<br>      }, <br>      &quot;links&quot; : { <br>        &quot;item&quot;: { <br>          &quot;<strong>href&quot;: &quot;/example/addresses/a933/e1fc-0f9d&quot;</strong><br>        } <br>      } <br>    },<br>    { <br>      &quot;id&quot;: &quot;2bc5–00dd&quot;, <br>      &quot;attributes&quot;: { <br>        &quot;display&quot;: “141 Shields Road, Sheffield, S12 9JX&quot;<br>      }, <br>      &quot;links&quot; : { <br>        &quot;item&quot;: { <br>          &quot;<strong>href&quot;: &quot;/example/addresses/a933/2bc5–00dd&quot;</strong><br>        } <br>      } <br>    } <br>  ],<br>  &quot;links&quot;: { <br>    &quot;collection&quot;: { <br>      &quot;<strong>href&quot;: &quot;/example/addresses/a933&quot;<br>    </strong>}<br>  }<br>}</pre><p>There’s plenty of JSON:API <a href="https://jsonapi.org/format/#document-structure">structure</a> in there, but the key takeaway is that we have three links, two pointing to the addresses in the user’s address book and one at the collection itself.</p><h3>Lifting the level of abstraction</h3><p>Having the server return URLs for the client to follow partially solves the coupling problem — it allows the server to change those URLs at will, without <em>necessarily</em><strong><em> </em></strong>breaking the client. The client still needs some additional information to be able to understand the semantics of these URLs. This additional information is conveyed in the form of <a href="https://tools.ietf.org/html/rfc5988#section-5.3"><em>relationships</em></a>.</p><p>A link relation in JSON:API looks something like this:</p><pre>&quot;item&quot;: { <br>  &quot;rel&quot;: &quot;item&quot;, <br>  &quot;type&quot;: &quot;application/vnd.api+json&quot;,<br>  &quot;href&quot;: &quot;/example/addresses/a933/e1fc-0f9d&quot;<br>}</pre><p>The important items here are the <em>relationship type</em>: rel: item, and the <em>resource type</em>: type: application/vnd.api+json. The former tells the client <em>what</em> the link points to — in this case the details of an item from a collection; and the latter tells the client how to parse that information, as well as how to request it from the server.</p><p>The <em>resource type</em> is included within the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept">Accept header</a> for subsequent client requests for that resource, forming a key part of the content negotiation mechanism.</p><h3>Profiles</h3><p>So our clients can now use relationship and resource types to navigate our server responses. The collection of all these semantic guides is called a <a href="https://tools.ietf.org/html/rfc6906"><em>profile</em></a> and is the cheat sheet a client needs to be able to understand what the elements of an API and its links <em>mean.</em></p><p>An API should publish a profile to help the client developers understand how to navigate it. There are some <a href="https://www.iana.org/assignments/link-relations/link-relations.xhtml">standard relationship types</a> that can be used, but you are free to make your own.</p><p>Having the client depend on the profile is how we free it from depending on URI templates. Now we can continue to honour the <em>meaning</em> of a link even when changing the link itself.</p><p>Adding in <a href="https://json-schema.org/">JSON Schema</a> documents gives us even more flexibility — but that’s a discussion for another day.</p><p>Profiles can also be appended to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept">Accept header</a> of an API request², giving us a form of versioning using <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation">content negotiation</a>. This can be useful if the profile changes, through extension or evolving semantics.</p><p>To make use of this, the client must append the profile to the Accept header of its requests:</p><pre>accept: application/vnd.api+json;<br>  profile=”www.depop.com/profiles/address”</pre><p>Then the server must advertise its content likewise in the response:</p><pre>content-type: application/vnd.api+json;<br>  profile=”www.depop.com/profiles/address”</pre><p>Here, the client is telling the server that it understands the semantics of this particular profile. Should the profile evolve over time, the server can advertise different versions of the same link adhering to different profiles — or even that a link supports both.</p><p>Newer clients can then prefer the updated profile to take advantage of the newer functionality:</p><pre>accept: application/vnd.api+json;<br>  profile=”www.depop.com/profiles/address_v2”,<br>application/vnd.api+json;<br>  profile=”www.depop.com/profiles/address”;q=0.9</pre><p>It should be noted when returning a response that may be <a href="https://tools.ietf.org/html/rfc7234">cached</a>, that the <a href="https://tools.ietf.org/html/rfc7231#section-7.1.4">Vary</a> header must include Accept; otherwise a client may be served a cached response for a profile other than the one that was requested.</p><h3>Conclusion</h3><p>What we end up with is a <em>state machine over HTTP</em>. This takes us to the pinnacle of the aforementioned <a href="https://www.martinfowler.com/articles/richardsonMaturityModel.html">Richardson Maturity Model</a> and is what is meant by the term <a href="https://restfulapi.net/rest-architectural-constraints/">HATEOAS</a>. Now we can truly say we have a <a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">REST API</a>!</p><p>More importantly though, it frees our clients from all that template filling and frees our server from the strong coupling that made evolving the API so tricky. All that and it simplifies our clients too, allowing them to be more generic.</p><p>So, at <a href="https://www.depop.com/">Depop</a> we’re aiming to adopt this style more often in our client facing Web APIs.</p><p>¹ Some required JSON:API attributes have been left out for clarity. See <a href="https://jsonapi.org/format/">the specification</a> for details.</p><p>² If supported by the media type in use. JSON:API <a href="https://jsonapi.org/format/1.1/#profiles">does support them</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15d4258951c4" width="1" height="1" alt=""><hr><p><a href="https://engineering.depop.com/using-hypermedia-in-web-apis-15d4258951c4">Using Hypermedia in Web APIs</a> was originally published in <a href="https://engineering.depop.com/">Engineering at Depop</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>