<?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 Ben XO on Medium]]></title>
        <description><![CDATA[Stories by Ben XO on Medium]]></description>
        <link>https://medium.com/@benxo?source=rss-c23cb6b72e15------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ewKxLNyyDu6tKnYFcd5tjg.jpeg</url>
            <title>Stories by Ben XO on Medium</title>
            <link>https://medium.com/@benxo?source=rss-c23cb6b72e15------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:05:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benxo/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[Live Tweeting Tracks from Serato DJ]]></title>
            <link>https://benxo.medium.com/live-tweeting-tracks-from-serato-dj-56ae66ff1ba9?source=rss-c23cb6b72e15------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ae66ff1ba9</guid>
            <category><![CDATA[dj]]></category>
            <category><![CDATA[live-streaming]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[lastfm]]></category>
            <dc:creator><![CDATA[Ben XO]]></dc:creator>
            <pubDate>Wed, 03 Mar 2021 21:02:38 GMT</pubDate>
            <atom:updated>2021-03-03T21:14:35.670Z</atom:updated>
            <content:encoded><![CDATA[<p>When there’s no tool for the job, sometimes you have to make your own!</p><h3>What is it?</h3><p><a href="https://github.com/ben-xo/sslscrobbler">SSL Scrobbler</a> is a tool I made — which I have used myself, every week, for over 10 years — to <a href="https://twitter.com/bdxposure">live tweet the tracks I play on my radio show</a>, as well as logging them to <a href="http://last.fm/user/ben-xo">my Last FM history</a> (“scrobbling” as it’s known on Last FM), amongst other bonus features.</p><p>One of the things I’ve always loved the most about DJing on the radio is the audience interaction, whether you have 10 listeners or 1000. But some tasks, such as answering requests for a Track ID, are a distraction and take you away from the craft — likely why few DJs do live tracklists at all. Indeed, some DJs purposefully enjoy the mystery of keeping people guessing — but I’ve always wanted to share what I like, and perhaps help support the artists when listeners go out to buy something that they’ve heard. After all, that used to be me — in the late 90’s and early 2000’s that was the main way I discovered new music myself.</p><p>The Last FM element is also important to me (and actually the original motivation for making this tool), and I’ll explain why shortly.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLIWaZjzScSs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLIWaZjzScSs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLIWaZjzScSs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2da28a9c77d5bc1e99262e741fba531/href">https://medium.com/media/b2da28a9c77d5bc1e99262e741fba531/href</a></iframe><h3>What motivated me to make this?</h3><p>If you’re a fan of drum &amp; bass radio you may or may not know that I’ve been doing a show on<a href="http://bassdrive.com/"> bassdrive.com</a> for the past twenty years. At the beginning, my weekly routine was to buy vinyl records and then have fun playing them on air — for myself, and a few hundred listeners, to enjoy. That’s been my routine every Tuesday evening ever since; but in around 2007, I switched my energy and focus to buying digital. After all, you can get more for your money that way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Eb8X_XMKRRf_PgEw" /></figure><p>My radio journey actually started a few years prior, when I had a Friday night show on one of London’s best pirate radio stations. It’s always felt good to have an audience enjoying the music I like to play. It’s great knowing that the music you play means something to people. That’s been especially relevant since lockdown, and I’ve received a number of messages from people to let me know that the music is what keeps them going.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ef1m2iBjFrUPpzho" /></figure><p>Despite this, the DJing is not actually my day job. I’m a software engineer by trade, and have worked for Last FM since 2008. If you don’t know Last FM (and many don’t), it’s a site that lets you keep a history of everything you’ve ever heard (when, and how many times) and it uses that information to work out new music you’ll probably enjoy. There’s a primer <a href="https://www.last.fm/about">here</a> — but millions of people use it, and Last FM has a very deep and very broad knowledge of music in every genre from any decade.</p><p>The key to this process is “<a href="https://www.last.fm/about/trackmymusic">scrobbling</a>” — the process of automatically logging your listening history, from wherever that may be, to Last FM. One of the Last FM mantras is “if it doesn’t scrobble, it doesn’t count”. Last FM has apps which support logging your listening history from many of the most common places people listen (<a href="https://www.last.fm/about/trackmymusic">the most popular ones are linked from here</a>). In the early days of Last FM this was CDs and MP3 collections. Last FM supported WinAmp and iTunes by installing the desktop app. These days, it continues to work extremely well with Spotify, YouTube and Apple Music, as well as any media player on Android. There are also browser plugins to support logging your playback from sites like Mixcloud, Soundcloud and many others as well.</p><p>And so, my motivation becomes clear. As someone who has been committed to this mantra for so long — both professionally and for my own listening and music discovery experience — the big hole in my listening history was the music I was playing on the radio each week, through Serato.</p><p>In 2010, there was no app which would allow this (and, Serato didn’t have the “public playlist” function either). I had to see if I could crack the problem myself.</p><h3>How does this differ from Serato’s live playlists?</h3><p>Serato’s live tracklist feature covers some, but not all, of the uses I had in mind. It only posts the tracklists to one place, which is the Serato website itself. Also, my preference is to tweet the title of a track once we’re a little way in — Serato’s live playlists only update once the track is marked as “played” inside Serato (which corresponds to when you progress from one deck to the next with new songs).</p><p>Last FM also has <a href="https://www.last.fm/api/scrobbling#when-is-a-scrobble-a-scrobble">quite specific rules about what counts as a “play”</a>, although they weren’t written with DJ mixes in mind. Ideally, if you only play a short part of the song (perhaps you dropped it in as a teaser), that doesn’t really count as a play.</p><p>There are a couple of other features I’ve added too, such as the ability to pop up a warning when you queue up a track that would break the DMCA streaming rules. If you’re unfamiliar with those, there are a few summaries <a href="https://help.live365.com/support/solutions/articles/43000533112-what-is-dmca-">here (live365)</a> or <a href="http://djcmedia.com/billing/knowledgebase.php?action=displayarticle&amp;id=4">here (djcmedia)</a>. In practise, this means it’s best to avoid more than four songs in a mix from the same artist, or three from the same album — and breaking these rules could make your mix unplayable on Mixcloud, for example.</p><h3>How does it work?</h3><p>As a developer, you always hope that perhaps there’s an API you can use to extract the information you want. <a href="http://wiki.winamp.com/wiki/Beginner%27s_Basic_Plugin_Guide">WinAmp</a>, <a href="https://docs.microsoft.com/en-us/windows/win32/wmp/windows-media-player-sdk">Windows Media Player</a>, iTunes / <a href="https://developer.apple.com/musickit/">Apple Music</a> and even <a href="https://developer.spotify.com/">Spotify</a> have fairly comprehensive APIs which let you access certain aspects of what song is being played.</p><p>However, Serato DJ does not. (You have to sign an NDA in order to be given access to create plugins).</p><p>So, I took another approach. Serato writes a history file as you play songs — it corresponds to what’s in the “History” view in the app. There is no documentation for this, it was painstakingly reverse engineered :) For more information on how it works, please take a look at <a href="https://github.com/ben-xo/sslscrobbler">the github link</a>.</p><h3>Things that may disappoint you ;)</h3><p>As I mentioned earlier, the great news is that this works, and has continued to work, for the last 10 years (with a few tweaks here and there along the way). The “bad” news is that, as something I originally made for myself, it does not have a clickable interface — it’s an app which runs in Terminal. Hopefully that won’t put you off. (Making a UI has always been on my to-do list — but I don’t need it myself).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H3IttvK6F4Uqdxcy" /></figure><p>I hope you found it interesting. I’ve also more recently made an app which has these same functions for tracks played on CDJ2000+ from USB sticks — something that many thought was impossible. That, however, is for another blog post!</p><p>Ben XO :: <a href="https://xo.am/">https://xo.am/</a> :: <a href="https://mixcloud.com/benxo">https://mixcloud.com/benxo</a></p><h3>Frequently Asked Questions</h3><h3>Can you make one for Traktor?</h3><p>I mean… I probably could. But I don’t use Traktor myself, so it would be hard to find the time to do it. The deepest layer of the app, extracting the playback information from Traktor, would be completely different to Serato.</p><h3>Why did you write it in PHP?</h3><p>There’s no good answer to this. In 2010, PHP was the language I knew best. It is not the right tool for the job, but it works. There have been <a href="http://projects.ssldev.org/2017/04/">some other projects</a> which have adapted this into other languages such as Java.</p><p>This article first appeared here: <a href="https://thedjrelay.com/guest-post-serato-scrobbler-deep-dive-and-backstory/">https://thedjrelay.com/guest-post-serato-scrobbler-deep-dive-and-backstory/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ae66ff1ba9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Last.fm To The Cloud Part 2: Scrobbling From Partner Apps]]></title>
            <link>https://benxo.medium.com/last-fm-to-the-cloud-part-2-scrobbling-from-partner-apps-758d1e74033d?source=rss-c23cb6b72e15------2</link>
            <guid isPermaLink="false">https://medium.com/p/758d1e74033d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[lastfm]]></category>
            <category><![CDATA[spotify]]></category>
            <dc:creator><![CDATA[Ben XO]]></dc:creator>
            <pubDate>Fri, 20 Nov 2020 10:28:51 GMT</pubDate>
            <atom:updated>2020-11-26T01:28:06.548Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Please note — Last.fm is hiring for engineers! Skip to the end for how to apply</em></p><p>A particularly challenging aspect of our migration was to seamlessly migrate the data we use for <a href="https://www.last.fm/about/trackmymusic">scrobbling</a> that’s received from users who’ve connected Last.fm to partner apps such as Spotify. The main reason it’s challenging is simply the scale. In any given month, we have well over a million users who expect that what they listen to is captured in their Last.fm history quickly and safely. This is a constant process — we receive data points from users hundreds of thousands of times per minute, all day, every day.</p><p>Perhaps it goes without saying that the number one priority for us when migrating this system into the cloud was to have no interruption to service.</p><p>The stages that this data goes through to reach our systems are, unfortunately, quite complex (although necessarily so). We have worked hard to make this invisible and seamless, with many design decisions along the way to minimise the risk of loss to our users in the face of typical risks that all internet services face, such a software or hardware crash.</p><p>This blog post focuses on the “top end” of the pipeline — closest to where the information users send us about their listening enters our system.</p><h3>Challenges</h3><p>One of the aspects that makes the system more complex than you might imagine is that the rules for counts as “one play” on a service like Spotify, and “one play” on Last.fm, are subtly different.</p><p>Here’s an example. Ever since the launch of Audioscrobbler (the precursor to the Last.fm library) over 15 years ago, Last.fm listeners have relied on <a href="https://www.last.fm/api/scrobbling">the rules of our algorithm</a>: to count as a play, you should listen to more than half of the song. The user library is a record of what you <em>chose</em> to listen to — and if a song comes on that you decide to skip, then you would not want it to influence your recommendations or other discovery features of Last.fm.</p><p>However, every service does things a little different. Spotify, for example, puts a song in your history if you listen to more than 30 seconds.</p><p>It’s differences like this which require us to go the extra mile to translate what we receive from users into a listening history that means the same thing throughout a user’s Last.fm library.</p><h3>Architecture</h3><p>The architecture we developed relies on users’ interactions with Spotify, which trigger messages about when they start or stop playing songs. And, although each user might only trigger one message every few minutes, this still amounts to hundreds of thousands of messages every minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZD98TndrHebCXwVoLQN-Q.png" /><figcaption>Messages from Spotify enter our system; a virtual player is ”simulated” to determine which songs to scrobble.</figcaption></figure><p>In order to capture them safely, the first thing we do is put them onto a resilient <strong>queue</strong>. This ensures that whatever happens next, the message will be dealt with eventually.</p><p>From the queue, we run the messages through a simulator (based on a State Machine) which works out how long each listener listened to a song for, and whether or not that would trigger a scrobble. (I won’t go into too much detail on this here — it would deserve a blog post of its own).</p><p>We also keep a cache of songs we’ve submitted, to prevent duplicates in case the queue needs to be replayed from an earlier point — and, we keep a log of recently processed messages, so that we can recreate the state of user’s playback in the case that one of the simulators needs to be restarted for whatever reason.</p><h3>Another Challenge: Offline Listening</h3><p>Spotify also has some additional challenges. Spotify Premium users can listen to a song “offline” (for example when on the subway, or on a flight) - and we don’t get information about this from them in real-time, although Spotify does record the songs into their history. As fans of Spotify ourselves, and living in London (with a large and famous subway network), we noticed this challenge right away!</p><p>Spotify does make available, through its API, <a href="https://developer.spotify.com/documentation/web-api/reference/player/get-recently-played/">the last 50 songs to which you listened</a>. One way to scrobble from Spotify would therefore be a “naive” approach such as to continually scrape their API for every Last.fm user’s history, to catch the ones played offline. This approach simply would not be possible: it would amount to millions and millions of API calls per day; that would be unacceptable to any online service, and is not acceptable to either Spotify or us.</p><p>So, how do we do it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VfZ2GIqTODM_r8N7dePxxQ.png" /><figcaption>The Spotify simulator outputs a queue of “recently seen” users, so we can check only active users who might have had a chance to listen offline.</figcaption></figure><p>Instead, we only check users who we know are active now, but haven’t seen for long enough that they may have had a chance to listen offline. These “online” and “offline” components complement each other, and share a cache in order to avoid scrobbling duplicates.</p><p>This architecture gives us some flexibility. Aside from the point at which messages enter our system, any one of these applications can be taken down for a short period of time, and then, when brought back, will continue where it left off.</p><p>It does, however, pose some interesting challenges when you need to migrate the system into the cloud!</p><h3>The Migration</h3><p>For this project it was essential to provide a set of diagrams to show what each stage of the migration needed to achieve. The diagrams in this blog post are similar to the ones we used internally during the migration process — I would recommend drawing the steps of a migration plan to help your team see how the pieces fit together.</p><p>It was also extremely important to us to be able to stop at any point, and to easily roll back to a fully functioning setup whilst maintaining data integrity - and the plan had to take this into account as well.</p><p>The first step of the migration was to install every app involved in the process in the cloud. As we already run all of our apps in Docker, it was straightforward to get them running in GKE. However, it’s important to point out that we must <em>never</em> run two simulations for the same user from the same data, as it could result in lost or duplicate scrobbles, both of which would inconvenience users in different ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*672xEldZD98QsBlMVAj7fw.png" /><figcaption>Replicating the pipeline in the cloud, with the new deployment dormant (shown with the queues empty).</figcaption></figure><p>The second step was to mirror the data used to bootstrap the recent history of events — the data used when the simulators restart. This was achieved using a RabbitMQ shovel to copy the backup message from one instance to the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*130wZle6gWHjLyvvUsIoEw.png" /><figcaption>Shovelling a copy of the backup queue from the old to the new.</figcaption></figure><p>The next step was to change the entry point for messages so that new messages arrive at the new queue only. Then, we let the simulators drain what’s left on the old queue until the pipeline stalls, with no more messages to process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwvCFPGyrec5saymb4zxqg.png" /><figcaption>Messages arriving at our original deployment are now sent directly to the new queue.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cn8GT9nIuCBGULYj6wVpUA.png" /><figcaption>The original queue is consumed until it’s empty, whilst the new queue begins to fill up.</figcaption></figure><p>Now, we can stop the simulators in the Datacenter, and start them running in GCP.</p><p>Finally, we can change the DNS so that Spotify sends us messages directly to our cloud deployment. This can take a while to go through, so both routes are maintained for the time being.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVL3CWHz45rPWnkQk8mGfw.png" /><figcaption>Messages can arrive at either deployment, but will all end up in the new queue. It may take a few days to fully switch over!</figcaption></figure><p>So far so good — but there were a number of unexpected problems we encountered whilst testing this migration which had to be resolved before we could do it for real!</p><h3>Latency</h3><p>It turns out that our apps were much more sensitive to network latency than expected. When each of these applications runs in the same datacenter, the communication time between each app may be under 1ms per message. But to do its job, the simulator must:</p><ul><li>Pull a message from the queue.</li><li>Check if it’s in the shared cache.</li><li>Potentially, put it in the cache if it’s not there.</li><li>Potentially, send a scrobble to our scrobbling system.</li><li>Check the cache to see if this message represents the first time we’ve seen a user for a while, and if so put a message on the queue used to check for “offline” listens.</li><li>If all of the prior processing for the message was successful, put the message onto the backup queue that’s used when the app restarts (so that it can get the state machine for that user back to the correct state if the simulator is restarted).</li><li>Finally, it must acknowledge the original message, to remove it from the queue, so it’s not processed twice.</li></ul><p>Whilst that entire process took under 10ms per message in our datacenter, during the period of the migration (where some software was running in the cloud but not all of it), the latency of many stages increased from under 1ms to around 40ms. 40ms is not a lot — but that represents a 40 to 50x reduction in processing speed for our application — instead of &lt;8ms, it could be up to 320ms per message. The consequence of this is that the simulator was no longer able to process several hundred messages a second. It could only process tens of messages per second— and would not have been able to keep up with the messages coming in.</p><p>The solution for this tricky situation was to re-engineer the simulator to be highly parallel internally, and to deal with messages in an asynchronous fashion. To understand how this could be achieved it’s worth noting two important properties of the data we receive:</p><ol><li>The data for each user must be processed in the same order that it’s received for it to produce the correct outcome.</li><li>However, the stream of data contains a mixture of messages from thousands of different users in any given minute — and different users’ messages are unrelated to each, so the order <em>between</em> them is not important.</li></ol><h3>Application architecture to solve the problem</h3><p>The most obvious change we made was to request large batches of messages at once, so that the latency is no longer per message, but per message-<em>batch</em>.</p><p>Unfortunately this wasn’t enough by itself. It does not help with the accesses to the shared cache, the scrobble submission, the re-queueing or the acknowledgement.</p><p>To bring the simulator up to speed, we made it thread the work into many parallel internal work queues, with any given user guaranteed to arrive on the same queue using a modulo of their user ID — but able to process users at a rate independent of each other.</p><p>As each message also has to be acknowledged, we also have an internal work queue used to send batches of acknowledgements — all acknowledgements have to come back through the same channel from which they were consumed. Also, we can’t consume another batch of messages until every message from the previous batch has been acknowledged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgjFbPxuSNWIQYGg1G1jGQ.png" /><figcaption>Messages from different users (represented by different colours) are split into different internal threads.</figcaption></figure><p>Now, it doesn’t matter if each thread can process far fewer messages per second, because they can process them simultaneously!</p><p>The offline scrobbler, which checks the Spotify API when a user has been seen recently in order to find any songs we missed through the usual process, also suffers from the latency problem. However, as this app is stateless, the solution is much simpler: we were able to simply start more instances of the app to achieve the necessary throughput.</p><h3>Lessons Learned</h3><p>The first lesson we learned was that sometimes all you have to do is scale up — start more instances of the app and the problem will be (temporarily) solved. The simplest solutions are often the best!</p><p>The other lesson we learned was that sometimes you really do have to make fundamental changes to your app to deal with high latency, a need we did not anticipate during the original development. This can be surprisingly hard.</p><p>However, we now have architecture which is resilient to future increases in traffic, and if it ever needs to be taken offline, can very quickly churn through the backlog of messages!</p><h3>Special Thanks</h3><p>Special thanks to <a href="http://last.fm/user/maciekwilk">Maciek Wilk</a> (senior developer at Last.fm) for help with diagrams and for achieving the speed improvements we needed to do the migration. Additional thanks to <a href="https://www.last.fm/user/kulot90">Matty Finnie</a> (our lead designer) for upgrading the diagrams in this blog post!</p><h3>Interested in working on problems like this?</h3><p>Last.fm is currently looking for engineers to help us solve problems and develop new features for our complex, service oriented system that serves millions of users every day. If you’d like to apply, send your CV and a cover letter to <a href="/service/mailto:jobs@last.fm">jobs@last.fm</a> !</p><h3>More articles in the series</h3><p>If you enjoyed this blog post you may also enjoy this post about <a href="https://medium.com/@benxo/last-fm-to-the-cloud-5e1de10ed58a">migrating our entire API with no downtime</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=758d1e74033d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Last.fm To The Cloud]]></title>
            <link>https://benxo.medium.com/last-fm-to-the-cloud-5e1de10ed58a?source=rss-c23cb6b72e15------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e1de10ed58a</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[lastfm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ben XO]]></dc:creator>
            <pubDate>Thu, 12 Nov 2020 18:28:11 GMT</pubDate>
            <atom:updated>2020-11-18T17:33:51.175Z</atom:updated>
            <content:encoded><![CDATA[<h3>Last.fm To The Cloud: How We Migrated Our API, Live</h3><p><em>Please note — Last.fm is hiring for engineers! Skip to the end for how to apply</em></p><figure><img alt="A cloud with the AudioScrobbler logo, and a ladder leading up to it." src="https://cdn-images-1.medium.com/max/1024/1*VJ1dT5BCdkhgvdV87HeCiA.png" /></figure><p>One of the more difficult challenges faced when moving the <a href="https://www.last.fm/">Last.fm</a> infrastructure into the cloud was to move our live API traffic, which receives tens of thousands of requests per second, with no disruption to the millions of users who use it on a daily basis. The aim was to make the change in a way that users would not even notice. But, for several reasons, this is tricky!</p><h3>Structure of our API service</h3><p>The API speaks to many of the same backends as the web pages on the site, but it has a few aspects which are specific to the API itself:</p><ul><li>a database of API keys and applications</li><li>a cache, accessed thousands of times per second, to support API Sessions (i.e. the data which enables users to be logged in within an app)</li><li>a cache used for rate limiting.</li></ul><p>The vast majority of this traffic comes through single URL: ws.audioscrobbler.com.</p><p>Our API Filter application deals with all of the methods on our <a href="https://www.last.fm/api">API page</a>, as well as the legacy Scrobble API, which is still actively used by some third party apps. It arbitrates between anonymous and logged-in features, and it has to accept users’ scrobbles quickly and reliably, whilst rejecting API abuse and ensuring that the service provided to apps is fast and fair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mMHfw2eUJWTRGdIPdoE1g.png" /><figcaption>The starting point.</figcaption></figure><p>Whilst deploying a second copy of all of these services is easy enough, the problem is ensuring seamless continuity from the point of view of users who are actively using the service at the time of the transition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*seah8AetTXG0KPDW2EZyLw.png" /><figcaption>Deploy to cloud.</figcaption></figure><p>From the outside, the main visible change is that the DNS entry for ws.audioscrobbler.com has to change to a new IP address. But those familiar with DNS will know that a change like this is not instantaneous. For some period of time — perhaps even days — traffic will still be sent via the old address. So, both the old and new deployments have to serve the same data, and a log-in through one entrypoint must create a session that works at either entrypoint. Failure to share the session cache could cause a user to be unexpectedly logged out of the app they’re using — perhaps more than once.</p><h3>Key Challenges</h3><p>One of the key challenges to overcome is that both the caching layer we use (Redis) and the database (Postgres) support replication, to keep two copies in different locations in sync. However, neither of them support having more than one instance which is the Primary — it’s only possible to write to one of them, meaning that at first, the new deployment must be configured to access the database and cache of the old deployment.</p><h3>Postgres</h3><p>Let’s deal first with Postgres. Fortunately for us, all API keys and application data exist in the Redis cache, and so the consequence of turning Postgres off entirely is limited: for a period of time, you would not be able to register a new API key (as a developer), but other than that there is no user visible impact. The strategy we chose here was to make the API database read-only, then export the data and import it into the new instance in the cloud, before pointing both new and old API stacks to the new database. The migration time here was under an hour — not so bad.</p><p>One point to note about dumping and restoring Postgres from your own deployment into a managed system (such as <a href="https://cloud.google.com/sql/">Google CloudSQL</a>) is that you probably want the database users to be managed by Google Cloud — and that means they will not be part of your database dump, and the login credentials will likely be different. So you have to study the options to pg_dump to make sure you are dumping the structure and data, but nothing extra such as the user accounts.</p><p>You may need to make some manual additions to the process to ensure the correct permissions on your tables — it’s worth examining all the queries your apps do to check you have all the required permissions covered!</p><p>It’s also extremely valuable to do a dry run, with a detailed set of repeatable instructions, to find out how long this process will take. Do it twice — sometimes, you’ll need to add extra steps to tear down data you created the first time, to ensure the process is truly repeatable at the time you need it to go smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOXz4-8EMn4lTUmkc8Zp7A.png" /><figcaption>Read only database — no new API keys possible during this configuration</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7uQjCzdSVAsub4kV7Dvaw.png" /><figcaption>Dump and restore the database (less than 1 hour)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOPdMFaWz8iJD63grEpbXA.png" /><figcaption>Use the cloud database directly — API app creation re-enabled</figcaption></figure><h3>Redis</h3><p>Redis, however, is another story. With tens of thousands of writes per second, it would not be possible to take it offline; and even the time taken to deploy a configuration change (were we to try to make the switch to the new Redis “instantaneously” with a configuration change to the app) could cause some users scrobbles to be lost, as they’re unable to create a session to submit them through. That would not be acceptable!</p><h3>Tailoring the approach to the types of traffic we serve</h3><p>At this point it’s worth examining the types of API traffic we receive, and adjusting the strategy in a more nuanced way.</p><p>Our API traffic breaks down broadly into three kinds:</p><ul><li>API requests to fetch information</li><li>API requests where a user is logging in, creating a session (perhaps for scrobbling or other logged-in features)</li><li>Scrobbles.</li></ul><p>Scrobbles themselves also break down into two kinds:</p><ul><li>Those which come through our recommended <a href="https://www.last.fm/api/scrobbling">scrobbling API</a> (Scrobble 2.0), which are part of a single long lived session</li><li>Scrobbles from the Scrobble 1 API, which, due to the way third party apps are typically implemented, often create a new session on a scrobble-by-scrobble basis.</li></ul><p>What this means for our session cache is that we actually have two kinds of sessions: long-lived ones (which can be active for months or even years) — these are used by apps such as the <a href="https://play.google.com/store/apps/details?id=fm.last.android">Last.fm Android app</a> — and short lived sessions which are created for a single use and then expire a short time later.</p><p>We decided that by splitting the cache into two caches — long lived, and short lived — we could migrate the two with different strategies. In fact, the short lived cache doesn’t even need to be kept in sync with replication. A brand new cache can be created just for the new deployment, and scrobbles coming in will be picked up seamlessly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqjB2jslConJMdxrYyXjjA.png" /><figcaption>The Rate Limiting cache is ready to go — it’s not necessary to replicate it.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0DG12glZtXVKZTITlnUaw.png" /><figcaption>At this point we split the session cache into short and long lived versions.</figcaption></figure><p>Scrobble 1 only uses this type of cache and so we could divert scrobble 1 traffic first, and independently of the rest of the API — a seamless change with no loss of data.</p><p>For the long lived cache, with long-lived sessions, we set up Redis with replication. Only one of the replicas can be written to, but switching which-is-which is quick (although not seamless). The only user visible impact would be that during the few minutes where we set the new Redis as the primary, and changed the configuration of the API endpoint to use it, a user would not be able to successfully log in to apps — but if they were already logged in, they would not notice any changes.</p><p>One of the problems with our use of Redis is that ours is around 30Gb in size. By default, Redis will try to save the entire thing to disk before transferring a copy to a replica. This takes time — it’s not uncommon for the first replication to take as long as half an hour.</p><p>Redis also will not do partial transfers to new replicas — it always does a full send. — so you must ensure a few things first, otherwise replication will never succeed.</p><ul><li>both the Primary and Replica must have long enough timeouts set in order to wait for the transfer without assuming the other has timed out.</li><li>You must set <strong>repl-timeout</strong> high enough, and <strong>repl-backlog-size</strong> large enough to account for any changes which happen in the mean-time. (Moving the short lived keys to a separate Redis helped considerably with this)</li></ul><p>For high availability, we use a Redis HA managed by Redis Sentinel. The cloud deploy of this required a little tricking in order to make the active primary behave as a replica of the Redis we’re bootstrapping from. This meant scaling it down to a single instance in GKE, so that Sentinel didn’t try to “correct” the problem by switching it back to being a replica of a different (empty) instance in GKE — for this we used <strong>kubectl --scale 1</strong> to temporarily turn off the other replicas. Only after the entire process is complete (and this Redis is the only active instance) can it be scaled back up.</p><p>Of course, in this state it’s fragile — you must ensure that the link between your premises and your cloud deployment does not go down during the migration.</p><h3>The final steps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6I3MrB4kFyYp-NE3K5XAQ.png" /><figcaption>This short-lived cache doesn’t need replication but the long-lived cache does.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Plb-eT6zQrOWS_LOuvITmQ.png" /><figcaption>At this point we can send all Scrobble 1 traffic straight to cloud with a DNS change!</figcaption></figure><p>With these changes in place, all that remained was to set the old deployment to forward all traffic to the new deployment, and the migration was complete!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1iK_WdoSWHva5tR1le3KQ.png" /><figcaption>Reroute all API traffic from one load balancer to the other. (Logging into apps temporarily disabled)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1iK_WdoSWHva5tR1le3KQ.png" /><figcaption>Break the replication and make the cloud Redis read/write. Normal service restored!</figcaption></figure><p>At this point, after breaking the replication from your original site, don’t forget to scale your Redis back up to a sensible number (we chose 3 replicas in different zones for redundancy).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYBJpltGeP_PS5jrV1CZjQ.png" /><figcaption>Change the DNS for the main API endpoint and wait for the traffic to migrate naturally.</figcaption></figure><p>With the DNS for the main API endpoint now changed, traffic will gradually migrate over to the new endpoint over the next few days.</p><h3>Lessons learned</h3><p>We learned three important lessons from this process.</p><p>The first is that many common database and cache applications are not easy to work with in a cross-site configuration. Databases which support multiple primaries would have made this process much easier. There are proxies we could have deployed to duplicate traffic, but these add yet more layers of complexity — and each of those proxies would require production-level alerting, monitoring and graphing in order for them to be deployed safely into production.</p><p>The second lesson is that sometimes it pays to make some small modifications to the application to support unusual situations you face. The change to split the cache into two types was simple — and it’s very important to know the properties and lifetimes of the types of data your app stores.</p><p>The third lesson is that diagrams speak a thousand words. We used diagrams like the ones in this blog post throughout the migration in order to help the team understand what needed to be done, in what order, and the implications. It’s easy to configure things for the final set up — but the short-term steps in between which ensure continuity are much harder to explain without pictures to refer to!</p><h3>Special Thanks</h3><p>Special thanks to <a href="https://www.last.fm/user/kulot90">Matty Finnie</a> (our lead designer) for upgrading the diagrams in this blog post!</p><h3>Interested in working on problems like this?</h3><p>Last.fm is currently looking for engineers to help us solve problems and develop new features for our complex, service oriented system that serves millions of users every day. If you’d like to apply, send your CV and a cover letter to <a href="/service/mailto:jobs@last.fm">jobs@last.fm</a> !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e1de10ed58a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>