<?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[The Silph Road - Medium]]></title>
        <description><![CDATA[The research, logistics, and devOps behind the world’s largest geolocation gaming community. - Medium]]></description>
        <link>https://medium.com/the-silph-road?source=rss----9845ace5d2b6---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>The Silph Road - Medium</title>
            <link>https://medium.com/the-silph-road?source=rss----9845ace5d2b6---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:50:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/the-silph-road" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Silph Town Map - rev 1]]></title>
            <link>https://medium.com/the-silph-road/the-silph-town-map-rev-1-b992f413eef9?source=rss----9845ace5d2b6---4</link>
            <guid isPermaLink="false">https://medium.com/p/b992f413eef9</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[openstreetmap]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Marco Ceppi]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 14:41:40 GMT</pubDate>
            <atom:updated>2017-03-19T14:41:40.272Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is a part two of an ongoing series about our map servers. </em><a href="http://blog.silph.io/2016/12/19/serving-our-own-slice-of-earch/"><em>Part 1</em></a></p><p>TL;DR: Retina tiles are being rendered and a whole new map style has been released.</p><p>While I promised a more technical dive into our infrastructure, this won’t be it. There will be a post following this one which outlines and details the nitty gritty of how run our basemap tileservers, which we’ve named “The Town Map”. It’s been three weeks since we made the switch to our own basemaps and a lot has been going on behind the scenes. As a result, any documentation of our infrastructure would be rendered obsolete within days of it’s publishing. We continue to improve performance, configurations, and experiment with alternatives: from different raster software to using vector tiles. As we conclude our tweaks and knowledge gathering I’ll make sure we publish a thorough write up of the deployment and, most importantly, how to replicate it.</p><p>Instead I want to talk about the new map design and other enhancements made to improve user experience. Like before this post will be split with more technical details towards the bottom. Since the launch we’ve gotten a lot of mixed feedback ranging from those loving the new map style to those less satisfied with its poor contrast and clutter. Under <a href="https://medium.com/u/8f45c4c06bb9">Dronpes</a> guidance, we’ve released revision 1 of the Silph Town Map! Here’s the changelog:</p><ul><li>Minor text fixes</li></ul><p>Okay, joking aside, anyone using the Atlas since the switch over will pick up a lot less yellow. The land has been changed to a more muted grey and all roads (motorway, trunk, primary, secondary, &amp; tertiary) are relegated to white with a darker grey stroke. Dronpes wanted to make sure we called attention to areas of interest. As such water, parks, and other areas where nests typically spawn have had their colors boldened. This should help identify potential unreported nests. Finally, buildings are only shown when more zoomed in and highways are highlighted in an orange-yellow color when more zoomed out. For the exact values, check our OSM-Silph repo on Github and most importantly pallete.css.</p><p>Second on the list of changes, is improved support for using the map while on a mobile phone. A lot of people have noticed that since our switch to self-hosting maps tiles were either fuzzy or the text was too small to read on phones. As a result we are now rendering retina tiles for all map users. This will insure that on High DPI/Retina devices, the map looks crisp and is easy to read.</p><p>Finally, <a href="https://medium.com/u/8f45c4c06bb9">Dronpes</a> has implemented measures to make sure if tiles fail to load, for whatever reason, they are retired. While you may stumble across a few “grey boxes” still, they should be far less likely and if they do appear will auto-correct themselves.</p><p>There is still room for improvement and you can expect a revision 2 of the map shortly. This will address what we’re calling “<a href="http://i.imgur.com/JDEiwrM.jpg">spaghetti</a>” when zoomed out due to highways taking over the map, continue colored tweaks, and more performance enhancements.</p><p>From this point forward I want to talk more on the technical side, with an overview on how we enabled retina tile rendering, how we produced the new Town Map theme, and some of the changes to improve performance.</p><p>In all honesty, the basemap tiles we’ve produced for the past few weeks were really rushed. This was and still is a lot of learning on the fly. We have a lot of the major problems under control now and are very intimate with the OpenStreetMap rendering services. As we’ve improved our knowledge gap, <a href="https://medium.com/u/8f45c4c06bb9">Dronpes</a> wanted to make sure we addressed the usability for maps. While it’s not terrible, it’s not what we wanted for the Silph Road Atlas.</p><p>Before going to deep, I want to refresh my diagram from my previous post. It’s a great high level diagram but glosses over a few parts which are pertinent to this post. What really happens, today, for our raster rendering is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*BiVYN5iR1pBR5tI6.png" /></figure><ol><li>A user on the nest atlas requests a tile from the CDN. If that tile has been cached, it’s returned</li><li>CDN makes a request to the loadbalancer</li><li>loadbalancer sends the request to a one of many tileservers</li><li>Apache receives the requests and is processed by mod_tile. If the tile exist on disk it’s returned, CDN caches the new tile</li><li>Rendered is invoked to generate a metatile</li><li>Rendered loads the Mapnik library</li><li>Mapnik uses PostgreSQL to look up relevant data at supplied metatile and renders raster</li><li>Rendered signals to mod_tile it’s completed the request, mod_tile returns the tile, CDN caches the new tile</li></ol><p>This is quite a lot to orchestrate. Thankfully, we’re reusing a lot from the Open Source community which makes this process much more straightforward. However, if we peel away the layers of this stack: the CDN, HAProxy, Apache, mod_tile, renderd, OpenStreetMap data; we’re left with the heart of this whole process, the rendering library called Mapnik.</p><p>Mapnik is the engine which translates OSM data to imagery and it does that using CartoCSS as a guide. CartoCSS is, as you may have imagined, a cascading stylesheet for cartography. Most web developers are familiar with the idea of a Cascading Stylesheet (CSS) as it’s what’s used to stylize websites, including this blog. In our haste to get the map server deployed we relied on an existing Mapnik theme: OSM-Bright</p><h3>Design</h3><p>OSM-Bright is a CartoCSS project that many use as a starting point to their mapping adventures. It provides a good mix of customizability via mix-ins as well as a pretty straight forward design. It served us well in the first week of running our own maps. We were able to quickly plan what changes we wanted to make and how to improve the experience. You can find the theme in it’s entirety in our <a href="https://github.com/silph-io/osm-silph">Github Repository</a>. While I won’t be detailing every change made I wanted to highlight a few things we learned in CartoCSS that add an interesting dimension to the map experience.</p><p>A note going forward, OSM does zoom levels from 0–19 where 0 is the entire world and 19 is basically a few acres of land. What this means is there are three main types of <a href="http://wiki.openstreetmap.org/wiki/Zoom_levels">zoom levels</a>. There’s a “low” level 0–4, a “medium/med” level of 5–10, and a “low” level, encompassing the rest. As a result, going forward when referring to high or low levels they are the inverse of what one might think. Low level is zoomed “out” and high level is zoomed in.</p><p>One thing we’ve changed, and are continuing to tweak, are the way roads are displayed. OSM data has a few different roadway types, but they break down into these categories: motorway, trunk, primary, secondary, standard, pedestrian, cycle, and rail. The first tweaks we made were at high levels of zoom, stripping out color indicators for automobile roadway types; the results were less clutter and more clarity on the map. This is the default zoom level, 15, for the Nest Atlas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*DvkVdaM0XeYa8V3a.gif" /></figure><p>Other things to point out, the “land” color is now grey instead of a yellow and buildings only appear on zoom levels over 15. However, you’ll notice as you decrease the zoom level, and zoom out, roadways will continue to disappear and motorway colors will change. The following is a comparison of OSM-Bright and the Town Map at zoom level 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*ZwI19gOFyJPzTUgf.gif" /></figure><p>Things to note, standard, and secondary roadways are removed, motorways are colored orange/yellow and states now have a border. For the latter, here’s the relevant CartoCSS to add in state boundaries:</p><pre>#admin[admin_level=&#39;4&#39;][zoom&gt;1] {<br>  line-color:@admin_2;<br>  line-width: 1.0;<br>  [zoom=2] { line-dasharray: 50, 35 }<br>  [zoom=3],[zoom=4],[zoom=5] { line-dasharray: 40, 28; }<br>  [zoom=6],[zoom=7] { line-dasharray: 30, 22; }<br>  [zoom=8],[zoom=9] { line-dasharray: 20, 17; }<br>  [zoom&gt;=10] { line-dasharray: 10, 8; }<br>}</pre><p>This snippet defines that for all <a href="http://wiki.openstreetmap.org/wiki/Tag:boundary%3Dadministrative#admin_level">admin points</a> with level of 4 — which is Provinces, Regions, and states — use the color for @admin_2, set the width of the line, then depending on the zoom level modify the line-dash. We haven’t been widely successful in getting a consistent dashed line for this boundary and will continue work to improve.</p><p>Here is the <a href="https://github.com/silph-io/osm-silph/compare/9ae7de89eb90b79dd8c1261b94e0522a13a48ec...silph-io:c5ccb7b2c077dce9a0aa5dfb27b29f0a3836ee10#files_bucket">entire diff from OSM-Bright to Town Maps</a> for a more in-depth overview of the changes made to manipulate the style.</p><h3>Retina tiles</h3><p>This was a much welcomed patch that was more straightforward than we imagined. renderd controls the configuration for tile rendering using the Mapnik library to produce the images. This is an example of the configuration we have today:</p><pre>[renderd]<br>socketname=/var/run/renderd/renderd.sock<br>num_threads=10<br>tile_dir=/var/lib/mod_tile<br>stats_file=/var/run/renderd/renderd.stats</pre><pre>[mapnik]<br>plugins_dir=/usr/lib/mapnik/3.0/input/ font_dir=/usr/share/fonts/truetype<br>font_dir_recurse=1</pre><pre>[default]<br>URI=/mappy-mc-mapface/<br>TILEDIR=/var/lib/mod_tile<br>XML=/src/OSMBright/OSMBright.xml<br>HOST=dev.maps.silph.io<br>TILESIZE=256</pre><p>Thanks to this contribution from <a href="https://lists.openstreetmap.org/pipermail/tile-serving/2014-July/001144.html">Ilya Zverev @Zverik</a> back in 2014, mod_tile and renderd now support a SCALE configuration setting. By doubling the SCALE and the TILESIZE we can produce Retina tiles. The resulting configuration block change is needed:</p><pre>[default]<br>URI=/mappy-mc-mapface/<br>TILEDIR=/var/lib/mod_tile<br>XML=/src/OSMBright/OSMBright.xml<br>HOST=dev.maps.silph.io<br>TILESIZE=512<br>SCALE=2.0</pre><p>This change has already been rolled out to all the tileservers and should be in effect.</p><p>In the next few days, once we’ve stabilized the environment I’ll be submitting the next installment in this series on how to duplicate this infrastructure at scale!</p><p><em>Originally published at </em><a href="http://blog.silph.io/2017/01/07/silph-town-map-rev-1/"><em>blog.silph.io</em></a><em> on January 7, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b992f413eef9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-silph-road/the-silph-town-map-rev-1-b992f413eef9">The Silph Town Map - rev 1</a> was originally published in <a href="https://medium.com/the-silph-road">The Silph Road</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving our own slice of earth]]></title>
            <link>https://medium.com/the-silph-road/serving-our-own-slice-of-earth-ec7758d8e7a7?source=rss----9845ace5d2b6---4</link>
            <guid isPermaLink="false">https://medium.com/p/ec7758d8e7a7</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Marco Ceppi]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 13:57:44 GMT</pubDate>
            <atom:updated>2017-03-19T14:08:39.685Z</atom:updated>
            <content:encoded><![CDATA[<p>Things have been pretty quiet on the Silph Road Ops. After ironing a lot of our <a href="http://blog.silph.io/2016/07/14/scaling-up-not-out/">scale issues</a> and <a href="http://blog.silph.io/2016/07/16/insights-with-datadog/">monitoring snafus</a> the servers basically run themselves. <a href="https://medium.com/u/8f45c4c06bb9">Dronpes</a>, Moots, and the team have kept on updating, upgrading, and releasing the Silph Road. The goal of this blog, and Silph IO, is to make sure the site stays up, stays healthy, and is cost effective to run. Today we’re announcing another step in making sure both goals are met.</p><p>When The Silph Road first launched, back in July and August and before the redesign with nest atlas, we used Google Maps for sightings. The invite system was largely due to connection limits with the free API key. While there are certainly ways around this, we believe in respecting TOS and licenses for all aspects of our stack.</p><p>As we moved into August, <a href="https://medium.com/u/8f45c4c06bb9">Dronpes</a> replaced Google Maps with Mapbox. Mapbox is one of the primary, third party, basemap providers. Effectively, they’re the underlying images that we overlay all the nest pins on. Due to some, frankly, aggressive and deceitful sales tactics; Mapbox went from our savior from invites to potentially a nail in our coffin. For specifics, <a href="https://medium.com/u/8f45c4c06bb9">Dronpes</a> covers this part in <a href="https://www.reddit.com/r/TheSilphRoad/comments/5jb99f/saving_the_nest_atlas_our_expenses_enterprise/">more details</a>.</p><p>Needless to say, just as when <a href="http://blog.silph.io/2016/07/30/the-cost-of-cloud/">Amazon’s cost</a> became untenable it was clear that Mapbox would not fit into our stack. Unfortunately, there seems to be a bit of a monopoly on basemaps. The number of companies providing this service are in the tens, the prices go from “developer account” to “call us”, and every company we shopped with couldn’t give us a price that works for our budget.</p><p>Before I go a little too far. I want to dive into the idea of basemaps a bit more and help explain some context. Most people are familiar with basemaps, though they don’t realize it. When you load up Google or Apple Maps, you’re presented with a canvas of a digitalized rendering of your location. Streets, building outlines, points of interest, etc. These are types basemaps. It’s the lowest level of a map display, much like a paper map of days gone by. From that basemap, Google, Bing, The Silph Road applies layers. Layers are anything that extends that basemap with supplementary data. Driving directions with a highlighted route is one example, traffic reports another, or pins showing nest locations. I mentioned previously basemap providers are in the 10s. Data sources for basemaps is even less. For the most part, there really only exists ONE public source of basemap data. <a href="http://openstreetmap.com/about">OpenStreetMap</a>.</p><p>OpenStreetMap (OSM) is much like The Silph Roads nest atlas, but for geographical data. Thousands of contributors scour their respective areas, collecting data about roads, parks, buildings, intersections, rivers, mountains, and any other geospatial data. These contributors update OpenStreetMaps database much like how you update/submit nests, or how you could edit a Wikipedia article. It’s an incredible effort, and a platform I’m a huge advocate for. Larger companies, like Google, Apple, etc keep their basemap data private. Smaller companies, like Mapbox, reuse OSMs data. This is possible because all contributions to OSM are licensed under the creative commons (CC-BY-SA). Which states, in brief:</p><blockquote><em>Share — copy and redistribute the material in any medium or format, Adapt — remix, transform, and build upon the material for any purpose, even commercially.</em></blockquote><p>This is interesting for many reasons, but the main reason is because while Mapbox is repackaging and reselling the generated images from this data, we could in effect, use the same data Mapbox has to produce our own tiles. In less than a week that’s exactly what we did. What follows is a much more technical breakdown of the process and initial cost analysis. But to summarize here for those not quite interested in the details, Mapbox final quote was $180,000/year while rolling our own infrastructure will cost less than $10,000/year (or $15,000/mo vs $987/mo!!).</p><p>I also want to introduce some OSM and basemap terminology. A lot of these concepts were new to me so I’d like to quickly define them:</p><ul><li><a href="https://wiki.openstreetmap.org/wiki/Elements"><strong>Element</strong></a>: the basic components of OpenStreetMap’s conceptual data model of the physical world consisting of nodes, ways, and relations</li><li><a href="https://wiki.openstreetmap.org/wiki/Nodes"><strong>Node</strong></a>: represents a specific point on the earth’s surface defined by its latitude and longitude</li><li><a href="https://wiki.openstreetmap.org/wiki/Ways"><strong>Way</strong></a>: an ordered list of between 2 and 2,000 nodes that define a polyline, typically used to represent linear features such as rivers or roads</li><li><a href="https://wiki.openstreetmap.org/wiki/Relations"><strong>Relation</strong></a>: a multi-purpose data structure that documents a relationship between two or more data elements (nodes, ways, and/or other relations)</li><li><a href="https://wiki.openstreetmap.org/wiki/Tiles"><strong>Tile</strong></a>: square bitmap graphics displayed in a grid arrangement to show a map, typically 256x256 pixel</li><li><a href="https://wiki.openstreetmap.org/wiki/Meta_tiles"><strong>Meta Tile</strong></a>: a server side construct of a square area consisting of 8x8 normal <strong>tiles</strong> (64 normal tiles) covering a square area of map which is 2048x2048 pixels</li></ul><p>After quite a bit of research earlier last week, it became clear that we’ll need a lot of CPU power and a lot of disk space. Thankfully, disk space these days is cheap. CPU time isn’t as expensive as it’s been in the past, but it would clearly be where a lot of investment went. Today, we run the majority of The Silph Road on Google’s Cloud Engine, for this I wanted to experiment with Amazon again. I know it costs more, but it’ll be a good marker of maximum costs and provides a baseline for performance comparisons. As we wrap up this initial experiment we’ll likely consolidate this elsewhere.</p><p>We started originally with a r3.xlarge (4vcpu / 30.5GB), this was updated to an r3.4xlarge (16vcpu / 122GB). I know I just went into how this was a CPU intensive process, but the first half is very VERY memory intensive. Once booted we attached two disks, one was 50GB io2 and an 800GB io2. These are ext4 partitions with the labels mapdb and mapdata.</p><p>From here we installed a slew of library packages, PostgreSQL 9.5, mapnik, mod_tile, Apache2, osm2pgsql. The end goal is to produce an architecture where all elements of OSM are stored in PostgreSQL and tiles are rendered from that data. This is what we’re striving for as an architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*poee1_g37N2HCYph.png" /></figure><ol><li>A request for a tile is made by the client. If the CDN has cached this tile it’ll return immediately.</li><li>CDN requests the tile from the tile server, caching the response.</li><li>mod_tile is triggered, if the tile exists on disk (tile_storage) it will be returned.</li><li>renderd is triggered, querying PostgreSQL for the elements, creating the tile image, and storing it on disk (tile_storage) mod_tile then returns the generated image.</li></ol><p>To start, we needed to load a copy of the OSM. The OSM project publishes <a href="http://planet.openstreetmap.org/">weekly dumps of their datasource</a>, licensed under the <a href="http://opendatacommons.org/licenses/odbl/summary/">Open Data Commons Open Database License</a>. They use a <a href="http://wiki.openstreetmap.org/wiki/PBF_Format">PBF format</a>, which compresses the data down to 34GB. This file is loaded into PostgreSQL using osm2pgsql, which looks something like this:</p><pre>osm2pgsql --slim -d gis -C 24000 --number-processes 4 /media/mapdb/planet-latest.osm.pbf</pre><p>This process takes, well, a while. It took 2.5 days on an r3.xlarge. On an r3.4xlarge it was down to 18 hours. osm2pgsql is quite clever in how it does it’s data import. First iterating over the raw data, importing it into temporary tables. Then using the PostgreSQL engine to compute, reduce, and index the data. This requires large amounts of CPU and Memory, which is why we used the r3.4xlarge. Once the import and processing was done, we moved the server to a c4.2xlarge. The final stats, for the planet, as of December 14th 2016 is: 3,636,347,854 nodes, 380,795,405 ways, and 4,626,332 points. Or, 710GB of PostgreSQL storage.</p><p>So, we have the data in a format that we can use to generate tiles! For this, we need renderd. renderd is a daemon service that runs in concert with mod_tile. mod_tile is an Apache module that interprets requests for tiles and checks for an existing Meta tile on disk. If they don’t, it’ll pass the request to renderd. renderd decouples the image create process from the Apache forks, allowing for Apache and mod_tile to process a lot more requests.</p><p>renderd, once given a zoom level, xtile, and ytile, will query the PostgreSQL database for the attributes in each of these tiles and compile a Meta tile using an XML/CSS combination to draw the elements. The result is a URL like https://tileserver/18/236773/161169.png to the following</p><p>Now that we’re getting tiles, we pre-rendered zoom levels 0 through 14. This takes about 62GB of space for the meta tiles. For this we use render_list, which simulates requests for tiles with given parameters. So -all tiles maximum zoom 14, minimum zoom 0, 50 threads, and maximum load of 22 on the machine. Or:</p><pre>render_list -m default -a -z 0 -Z 14 -n 50 -l 22</pre><p>Okay, we’ve got the tools, we’ve got a cache of tiles, we have a rendering server, and we’ve got all the map data we need. Next was a stress test. As we learned <a href="http://blog.silph.io/2016/07/14/scaling-up-not-out/">in the past</a>, just having a single server regardless of how beefy it is, will eventually succumb to too much load. There’s a ton of ways to go about stress testing, for the quickest route we decided to roll the single server into production for a short period of time. During that time we were able to gather enough information from load on the servers, number of tiles requested in a minute, to what PostgreSQl does under full force. Based on that it was clear we needed to increase our rendering capacity. Thankfully, renderd scales!</p><p>There’s not a lot (okay, none so far) in the way of documentation for this. After a bit of trial and error, it turns out to be pretty simple. To facilitate this, I first mounted an elastic file system. For Amazon this is EFS, but CephFS, NFS, or really any other software that presents a filesystem over the network will do. Then I setup two additional servers with mod_tile, apache, everything with the exception of PostgreSQL. This didn’t turn out exactly how I expected. In the end, removing Apache and setting up renderd to use the other servers as “slaves” meant less overhead and better management.</p><p>We’ve scaled this out for the initial bump, with five render slaves running on c4.xlarge amazon instances we’ve started performing the roll out. <a href="https://medium.com/u/8f45c4c06bb9">Dronpes</a> has implemented a staged rollout for the atlas, which went live Sunday night. Over the next few days you may end up seeing a slightly different map and there’s a chance you may hit some oddities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*o4PP780vPBNQS-wh.png" /></figure><p>If you come across black/grey squares or other issues, try zooming out one level and zoom in. You’ve hit a bit of a peak moment in the server&#39;s map generation not previously accessed.</p><p>I understand this post is a bit light on the actual how to. The following post will dive deeper into this and our plans around basemap generation. For now we’re happy with the progress, as we run this in full we’ll report back to the community on cost and improvements.</p><p>We had less than a week to build a tile server and basemap system, this is by far not the last iteration. In the coming days we’ll be stabilizing the platform, updating tile styles, and making sure our tiles are as up to date as the upstream OSM data source.</p><p><em>Originally published at </em><a href="http://blog.silph.io/2016/12/19/serving-our-own-slice-of-earch/"><em>blog.silph.io</em></a><em> on December 19, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec7758d8e7a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-silph-road/serving-our-own-slice-of-earth-ec7758d8e7a7">Serving our own slice of earth</a> was originally published in <a href="https://medium.com/the-silph-road">The Silph Road</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving clouds without downtime]]></title>
            <link>https://medium.com/the-silph-road/moving-clouds-without-downtime-656fcc364a1b?source=rss----9845ace5d2b6---4</link>
            <guid isPermaLink="false">https://medium.com/p/656fcc364a1b</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Marco Ceppi]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 13:44:59 GMT</pubDate>
            <atom:updated>2017-03-19T13:44:59.207Z</atom:updated>
            <content:encoded><![CDATA[<p>We’re just shy of two months running on the new scale-out infrastructure and a common thread throughout those two months is the cost of running in the cloud.</p><p>We first trimmed down cloud costs by <a href="http://blog.silph.io/2016/07/18/CDN-CDN-CDN/">moving to a CDN</a>. We then followed up by moving to an <a href="http://blog.silph.io/2016/07/30/the-cost-of-cloud/">even cheaper CDN</a>. Finally, resting where we are today, with <a href="https://maxcdn.com/">MaxCDN</a> which has actually been a good balance of cost and quality.</p><p>However, this is a community run website, and to make sure we keep the lights on — so to speak — we need to make sure we’re getting the best deal for everything we do.</p><p>To date, The Silph Road runs on Amazon’s Web Services. While I’ve expressed some disdain towards them, they are arguably the largest cloud vendor. As a result, AWS comes with a lot of features, is quite robust, and well trusted.</p><p>In our <a href="http://blog.silph.io/2016/08/30/postmortem-tuning-app-and-database/">last post-mortem</a> one of the questions in the comments was why we don’t leverage more of these features. Our architecture is rather simple where we just consume a set of machines, IP addresses, and disks.</p><p>Amazon alone has over 50 additional services, from databases as a service, dns as a service, object store as a service, containers, email, queue messaging, the list goes on. These are quite enticing. You get an endpoint + credentials and don’t have to manage anymore infrastructure. However, it comes at a cost — and the most expensive of those costs is vendor lock-in.</p><p>Last month&#39;s, August 2016, Amazon bill was $1,200. For some that’s a lot, for others not so much. Regardless, it’s more than we want to pay a month for <em>just</em> cloud instances. When you start adding up the cost of the CDN, and other services we depend on, we reach a point where keeping the lights on is a real concern. As a small team, we must be agile and swift. To be agile we try to avoid cases where we’re married to any one platform — or tool.</p><p>When it comes to public clouds, there’s actually quite a bit of choice. In addition to Amazon, there’s clouds from other industry titans: Microsoft’s Azure Cloud and Google’s Compute Engine, but also other budding clouds: Rackspace, OVH, Joyent, CloudSigma, the list goes on. After spending quite a bit of time mapping out projected costs of the infrastructure, Google’s GCE seemed to offer the best performance for price point. Now that we have a cloud chosen, it was time to do the migration.</p><p>Normally, when it comes to migrations of this scale a maintenance window is usually announced, then a few hours are spent moving everything over. We’re not a Fortune 500 company or some large platform, and maintenance windows/scheduled downtimes are so old school. Here’s how we pulled off the migration with less than 2 mins of interrupted service.</p><p>The first step was to get the new cloud instances up and running. To do that we ran the following:</p><pre>juju bootstrap silph.io-prod1 google/us-east1<br>juju deploy -n 4 cs:~silph.io/silph-web --constraints instance-type=n1-standard-2<br>juju deploy mariadb --constraints instance-type=n1-standard-2<br>juju deploy redis juju deploy haproxy</pre><p>So to lay out what we’ve done:</p><ul><li>Create a Juju controller on Google’s US-East1 region called silph.io-prod1 (Amazon’s controller is called silph.io-prod0)</li><li>Deploy four units of the silph-web charm. This charm is all the operational knowledge of how to install, configure, and manage the Silph Road web app</li><li>We tell Juju we want these to be on the <a href="https://cloud.google.com/compute/docs/machine-types#standard_machine_types">n1-standard-2 instance types</a>.</li><li>Deploy MariaDB, Redis, and HAProxy from the charm store. These are charms created and maintained by the upstream vendors or upstream communities</li></ul><p>Now we’ve got seven machines running, four are our web application and three are split between database, cache, and load balancer. Right now they’re all running but unconfigured. The web application doesn’t know where the database or cache servers are and the loadbalancer doesn’t know where the web application is. In the Juju Charms, the relations are encapsulated as code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*0ibeJ8euCrUMighR.png" /></figure><p>So the silph-web charm says it consumes something called “mysql” and “redis”, and provides something called “http”. Likewise, redis and mariadb provide “redis” and “mysql” respectively, and haproxy consumes “http”. This mapping allows for an explicit exchange of information, like connection details, without me or anyone else having to interfere. To make these connections we just issue the following:</p><pre>juju add-relation silph-web mariadb<br>juju add-relation silph-web haproxy<br>juju add-relation silph-web redis</pre><p>We also need to bolt on our monitoring!</p><pre>juju deploy cs:~silph.io/datadog<br>juju add-relation datadog haproxy<br>juju add-relation datadog redis<br>juju add-relation datadog mariadb</pre><p>We then need to pass in some configuration, things like our access key for Datadog and the SSH private key to access our code repositories</p><pre>juju config silph-web ssh-key=$(cat $HOME/.ssh/silph-repo)<br>juju config datadog api-key=&quot;my-secret-api-key&quot;</pre><p>It’ll take a few mins for the environment to go stable, this is because distributed systems will always take a varying amount of time to converge. Since we’re using Juju and Charms, I don’t have to worry about the ordering of events. In fact I could have run any of the aforementioned commands in any order and gotten the same results. Now that everything is idle and converged we can inspect the status with juju status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/0*vMawkLoDWEEJlb2F.png" /></figure><p>Now it’s time to do a little razzle dazzle. To prepare we need to do the following:</p><ul><li>Set DNS time to live (TTL) to as low as humanly possible</li><li>This will allow us to change the IP address for thesilphroad.com and hopefully have people’s browsers get the new address quickly</li></ul><p>We lowered the TTL ahead of the move to make sure everyone had the new lowered value. Now the following will happen all in the same 1 minute window:</p><ul><li>Change IP address in nameserver to new HAProxy IP address</li><li>Take a snapshot of the database</li><li>Disable the database server on old environment</li><li>Restore snapshot of database to new database server</li><li>Update old loadbalancer to send all requests to the new loadbalancer</li></ul><p>As you can see, it’s a lot of moving parts! We disable the old database server on the old host after the dump to make sure no new data is written. The downside is while the database is being restored to the new server people will get an “Oops” message.</p><p>It only takes about 45–60 seconds to move the database snapshot to the new server. Once it’s moved over we can’t count on DNS being updated, so we set the load balancer to redirect all requests to the new server. The result is a ~90 second window where the site is unavailable.</p><p>While I’m quite happy with the result, I’ve got plans on how we can actually do a full switch over with zero down time. As we’ve got more migrations coming for the infrastructure I’ll cover those plans in another post.</p><p>For now we’re on Google and so far things seem to be going pretty well!</p><p><em>Originally published at </em><a href="http://blog.silph.io/2016/09/11/moving-clouds/"><em>blog.silph.io</em></a><em> on September 11, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=656fcc364a1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-silph-road/moving-clouds-without-downtime-656fcc364a1b">Moving clouds without downtime</a> was originally published in <a href="https://medium.com/the-silph-road">The Silph Road</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Application and database tuning]]></title>
            <link>https://medium.com/the-silph-road/application-and-database-tuning-bd53bbf2f4f6?source=rss----9845ace5d2b6---4</link>
            <guid isPermaLink="false">https://medium.com/p/bd53bbf2f4f6</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[postmortem]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Marco Ceppi]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 13:33:31 GMT</pubDate>
            <atom:updated>2017-03-19T14:09:40.862Z</atom:updated>
            <content:encoded><![CDATA[<p>The first half of this blog post will be a postmortem on the events that occurred today resulting in long load times, 502 gateway errors, and spotty availability.</p><h3>Timeline</h3><ul><li>17:19UTC Trainer Tips release a <a href="https://www.youtube.com/watch?v=bLhwgS9LzVo">video</a> on Youtube linking to Silph Road</li><li>17:21UTC Average response time go from 100ms to 21,000ms per request</li><li>19:15UTC Patches are applied to NGINX and PHP-FPM to address latency in EBS volumes</li><li>19:17UTC Response time drops to 900ms (avg)</li><li>19:19UTC Response time increases to 29,000ms (avg)</li><li>20:17UTC MySQL identified as bottleneck in performance</li><li>20:31UTC Code changes deployed to optimize queries during user registration</li><li>20:39UTC Database indexes updated to help optimize SQL traffic</li><li>20:43UTC Second bottle neck identified in user registration</li><li>21:05UTC Code changes deployed, including several query optimizations</li><li>21:07UTC Database indexes updated again</li><li>21:09UTC Response time drops to &lt;100ms (avg)</li></ul><p>Up until recently user access to The Silph Road was metered by invite bursts, as such user registration code paths were not as battle tested as other parts of the site which were tweaked and repaired over the course of July. From the above postmortem several lessons were learned:</p><ul><li>Monitoring was not properly configured so operations wasn’t notified of a problem until several hours after the incident started. The duration of this outage could have been drastically reduced. Going forward we’ve improved our alerting and pager duty. Notifications will now reach those who need to know much sooner.</li><li>The database and web application make use of methods which are costly to performance. While the immediate ones have been patched a review of the most common and longest running queries will help us find and fix the remaining.</li><li>Amazon’s EBS disk continues to be our largest web tier bottle neck. We are evaluating other cloud platforms in the same fashion <a href="http://blog.silph.io/2016/07/18/CDN-CDN-CDN/">we’ve done for CDN providers</a>.</li></ul><h3>Details</h3><p>So, we got the formalities out of the way. Lets take a look at what we uncovered at each step of the incident and how we resolved the problems presented in todays incident.</p><h3>There’s problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AyYqojj0Sz6PABKc.png" /></figure><p>The first indication that we had a problem was the following (numerous) emails:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4GUtm50T2n0BXNoe.png" /></figure><p>I get these from time to time, and in the past it’s typically been due to disks filling up and causing the agent to crash. When these hit my inbox at 17:20ish I surmised it to be just that, logged into each node, checked disk space, and restarted the agents on web0 and db0. This was the first indiction of a problem and because the alert wasn’t clear in describing the problem, diagnosis began and ended at what has typically caused this alert in the past.</p><p>To address this we’ve used Datadog’s awesome alerting framework and expanded our breadth of alerts. Now whenever things like the database server go over a 15min load of 15 or 1 min load of 30, I will get unique set of alerts.</p><p>The second identification of a problem came when Dronpes pinged me on chat, shortly after the email notifications. Because of how mobile I am, chats always appear on my phone and I typically have the chat desktop app running in chrome. My phone being on lower battery avoided it from running the chat’s background process to notify me.</p><p>Also, because of my zealous use of Google Chrome, I have an add-on called “The Great Suspender” which suspends inactive chrome tabs when I’m on battery power. Since I typically have two chrome sessions and 120 tabs between the two of the open, it saves my battery life while not losing my place. However, the chat tab was not configured properly, so instead of it staying unsuspended it also got closed down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RnPBPAjB4bW8pQOb.png" /></figure><p>If I had my battery pack for my phone, or the tab managed properly, notification of this would have been pretty instant. Going forward these have both been corrected. In power saving mode my chat application is still allowed to run, I picked up 16,500 mAh battery pack for when I’m mobile, and the tab in chrome is adjusted.</p><p>Finally, we’ve opened up our <a href="https://p.datadoghq.com/sb/a42d80f38-e1f5b6fc5e?tv_mode=true">operations dashboard</a>. Curious if the app is having problems or it’s just you? Check out the dashboard to get the same overview we use.</p><h3>502 Gateway Error</h3><p>When investigating an error like this, the first place to look is the source of the error. Anyone who’s used NGINX is aware of this lovely, albeit boring, 502 error page. Essentially, this means that NGINX can’t communicate with the Gateway (PHP-FPM). Looking at the logs, a lot of this was seen:</p><pre>2016/08/30 17:24:07 [error] 24736#0: *69227539 connect() to unix:/var/run/php5-fpm.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: 10.142.182.3, server: _, request: &quot;GET /users/registration HTTP/1.1&quot;, upstream: &quot;fastcgi://unix:/var/run/php5-fpm.sock:&quot;, host: &quot;thesilphroad.com&quot;, referrer: &quot;https://ssl.reddit.com/&quot;</pre><p>Essentially, php-fpm isn’t able to handle this request, but the CPU and memory consumption on the servers is low. So, that’s right, you guessed it. <a href="http://blog.silph.io/2016/07/16/insights-with-datadog/">Amazon EBS disks</a> have come to haunt The Silph Road again. To work around this we actually moved to a TCP Socket instead of a unix socket. This is so counter intuitive it’s almost twilight zone-esque.</p><p>Normally, this would be patched in the charm and then an upgrade would occur, but since we’re firefighting in production we tested it on one server then rolled it out to the remaining. This removed the errors from cropping up in the log, but didn’t really address the overall performance.</p><h3>Digging for a reason</h3><p>With NGINX silenced we move further down the stack to the next bottle neck: the database server. This is ultimately where the most ground was made up in “fixing” the site. Looking back at Datadog we realized the load on the database server was quite high.</p><pre>20:15:27 up 34 days, 15:33, load average: <strong>689.12</strong>, <strong>512.28</strong>, <strong>401.01</strong></pre><p>On an average day, this is the typical load average on this server.</p><pre>22:46:27 up 35 days, 17:16, load average: <strong>1.12</strong>, <strong>5.28</strong>, <strong>3.01</strong></pre><p>So the server’s <a href="https://en.wikipedia.org/wiki/Load_(computing)">load</a> is 600 times higher than what we normally operate at. It’s safe to say, at this point, our database server is the cause of ballooning load times.</p><blockquote><em>On a single CPU system a load of 1.73 means that of the there were on average 1.73 runnable processes, 0.73 had to wait to be processed. A load value of 7.98 means the system was overloaded 698% on average (7.98 runnable processes, 6.98 processes had to wait for a turn to use the CPU on average.</em></blockquote><p>So CPU load doesn’t indicate CPU utilization, it’s more an indication of the queue of things waiting to be processed. If you’ve ever done intensive work on a computer and noticed it start to become sluggish it’s because the queue to process things is more than the CPU can handle at that time. With our setup we have two cpus on this machine, so a load of 2.0 is an empty queue, a load of 689 means that the system is overloaded in the tens of thousands of percent.</p><h3>Tuning a MySQL server under stress</h3><p>To avoid getting bitten by Amazon’s poor disk IO we put all the data for MariaDB on SSD drives. This has increased the amount operations we can perform given the relatively small instance size. When investigating why the MySQL server was so overloaded the first thing was to jump into a MySQL session and just see what was running.</p><pre>$ mysql<br>MariaDB [(none)]&gt;</pre><p>From here, we ran show processlist; which dumps the list of running processes on the MySQL server. This returned over 1500 rows. That’s 1500 MySQL threads being processed. The list of processes includes the queries being run. From there we saw queries, like the following, taking anywhere from 4 seconds to greater than 30 seconds to complete.</p><pre>SELECT COUNT(*) AS `count` FROM `users` WHERE `username` = ?</pre><p>There are a few things problematic in this query. The first is COUNT(*), which can be quite expensive when compared to alternatives, such as COUNT(1). Ultimately, this query is looking to see if the username exists already exists during the registration process. The increase of user traffic to the site and the removal of the access code gate brought to light these two problems:</p><ul><li>COUNT(*) isn’t as efficient as other means to determine if a field exists in the database</li><li>username wasn’t being indexed</li></ul><p>The second problem was the more costly one. The users table growing by a few hundred entries every minute compounded the cost of look up times during user registration, creating this bottle neck. The longer these processes took, the more other processes had to wait, the higher the load on the server. All of this backsup into the web application and causes it to timeout and respond slowly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2dtXgJJNSUIB8NRe.png" /></figure><p>After fixing a few of the queries in the code and creating new indexes in the users table, MySQL was able to churn through these requests much quicker. The results are less processes waiting, a lower load, and the application can respond quicker.</p><p>Using Juju, we tuned MariaDB’s configuration to get more breathing room. To accomplish this, we increased tmp_table_size and max_heap_table_size allowing for those queries which require temporary tables to run efficiently.</p><p><em>Originally published at </em><a href="http://blog.silph.io/2016/08/30/postmortem-tuning-app-and-database/"><em>blog.silph.io</em></a><em> on August 30, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd53bbf2f4f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-silph-road/application-and-database-tuning-bd53bbf2f4f6">Application and database tuning</a> was originally published in <a href="https://medium.com/the-silph-road">The Silph Road</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The cost of cloud]]></title>
            <link>https://medium.com/the-silph-road/the-cost-of-cloud-439d8a1d7c1f?source=rss----9845ace5d2b6---4</link>
            <guid isPermaLink="false">https://medium.com/p/439d8a1d7c1f</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Marco Ceppi]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 13:20:25 GMT</pubDate>
            <atom:updated>2017-03-19T13:20:24.885Z</atom:updated>
            <content:encoded><![CDATA[<p>The infrastructure has been humming along so far, and except for the occasional blip during a code release it’s become clear we’ve done a stellar job of tuning the infrastructure as well as the code using <a href="http://blog.silph.io/2016/07/16/insights-with-datadog/">data to help drive optimizations</a>. So, it’s getting close to the end of month, a time when bills are commonly due. Peeking into the Amazon account billing board a surprise awaited: the cost of our popularity so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kXyRgxGlHYLjzpq9.png" /></figure><p>Ouch. There’s a common saying that the cloud is expensive, so I steeled myself for the bill. However, I wasn’t prepared for the cost of a CDN. A CDN which we celebrated not too long ago. With every decision there’s a trade-off, with being “on rails” and super focused this past month, these pros/cons tradeoffs increase in risk. This is why data-driven operations is so important. We’re going to have to eat this cost and this choice, something we should have been monitoring closer — sooner. So we’ve identified two problems. The first, we’re paying way too much for a CDN. The second, we’re serving too much data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rmUqnCV0ZseT_tF2.png" /></figure><p>The first problem is a little harder to fix and requires engineering time. The second problem, however, is something we can action upon today. After taking a look at our throughput I turned to the internet in order to quickly find a CDN server which could offer the infrastructure for the amount of data we’re pushing out while still being cost effective.</p><p>I ended up landing on <a href="http://www.cdncalc.com/">CDN Calculator</a> which, while rudimentary, it was able to help scope my focus. In following the trend of the past month we’re looking for breathing room, another $3,000+ bill will severely prohibit The Silph Road going forward. After entering all the data that we’ve collected for the past two weeks on CloudFront, <a href="http://cdnify.com/">CDNify</a> seemed like the best intermediate solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L30Lx_8pEIusOL5x.png" /></figure><p>To quickly answer why I chose CDNify over JoDiHost, I briefly looked at both and at the end of the day, CDNify seemed to be a pure CDN company. This means they’ll have a much more focused user experience and provide us with more insights into our data. This is something that Amazon lacks in CloudFront. The major difference between this CDN and AWS CloudFront: AWS CloudFront is backed by S3, CDNify simply caches from our origin. This means in order to warm the cache we have to let loose a bunch of traffic into the loadbalancer. I knew this would spike things, but I didn’t realize fully the implication until we made the switch in the site configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t5PJFYg-JwovqbR9.png" /></figure><p>This isn’t really a bad thing, we can handle a flux like this, but it does put undue strain on the servers. Servers, which we’ll be scaling down very soon to continue saving costs. As a result, we can’t have assets being fetched from our servers every 24 hours (or however long we make the TTL) — same thing when we update assets on the site. This is where I really like CDNify’s interface. I was able to, very quickly, repoint the origin from thesilphroad.com to our S3 bucket which was originally backing CloudFront! This means we still offload our traffic, and the amount of traffic hitting S3 is very low and predictable, which we can plan for.</p><p>Over the next few days we plan to work on making image sprites of all the multi-image assets. This means instead of 151 pokemon images that have to be loaded 151 times per page view, it’s a single PNGcrush’d image that’s distributed once from a CDN cache. This will cut down on the amount of bandwidth used as well as the number of requests to the CDN — both things that we’re charged for.</p><p><em>Originally published at </em><a href="http://blog.silph.io/2016/07/30/the-cost-of-cloud/"><em>blog.silph.io</em></a><em> on July 30, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=439d8a1d7c1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-silph-road/the-cost-of-cloud-439d8a1d7c1f">The cost of cloud</a> was originally published in <a href="https://medium.com/the-silph-road">The Silph Road</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saving user sessions (and our disks)]]></title>
            <link>https://medium.com/the-silph-road/saving-user-sessions-and-our-disks-775a8f5ddcfa?source=rss----9845ace5d2b6---4</link>
            <guid isPermaLink="false">https://medium.com/p/775a8f5ddcfa</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Marco Ceppi]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 13:06:28 GMT</pubDate>
            <atom:updated>2017-03-19T14:10:18.909Z</atom:updated>
            <content:encoded><![CDATA[<p>One side effect of the move to <a href="http://blog.silph.io/2016/07/14/scaling-up-not-out/">multiple, scaled out, architecture</a> is how user sessions are saved. Whenever you log into the server you get back a cookie with you session identifier. This tells the server who you are without you having to log in every time. On the server, it stores a copy of that identifier to validate that you are who you are and you still have a valid login. Before the move, when everything was on a single machine it was easy to validate these sessions. You always visited the same machine and your server-side session was there.</p><p>Since our move, when you access the site you may actually hit one of five machines. If you login to server 1 and on the next page view end up on server 3, the code doesn’t have your copy of the server-side session and you’re forced to log in again!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*5E1OPvrbCmTimCu2.png" /></figure><p>When we set up the loadbalancer we used an additional cookie configured at the loadbalancer. Whenever you first hit the site, if the cookie isn’t set, the loadbalancer picks one of the five servers to send you and sets the cookie value to that server. Going forward, every request you make will always end up at that server. However, the cookie is designed to expire frequently, why? Well we move servers around all the time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19704989cfd3f966df7c1459c98451d1/href">https://medium.com/media/19704989cfd3f966df7c1459c98451d1/href</a></iframe><p>Ultimately, it’s just not a solution that will scale. Something else we noticed, as we got a jump in traffic, the performance of the site degraded again. This was the same <a href="http://blog.silph.io/2016/07/16/insights-with-datadog/">pattern of degradation</a> we say before moving to a CDN: PHP processes ballooning out of control on IO wait. On waiting for disks!</p><p>When we started drilling in, one thing we noticed was a lot of time spent getting a file written to disk. Ah! One thing that wasn’t accounted for, the more people visiting the site, the more session files that get created. This locks the disk up just as bad as before when we were only reading from the disk for assets.</p><p>In addition, we’ve been getting a lot of reports of “login” loops. Where after authenticating a user has to authenticate again several more times before it “sticks”. This presented us with the ability to kill two birds with one stone: offloading sessions from the disk much like we did assets with CDN. To do this, we’ll need a datastore that can handle the amount of traffic without adding more overhead.</p><p>For this, Redis was the obvious option. We’ve looked at memcached and I’ve used it in the past but when we tried to make the switch during the original setup, it ended up being a huge bottle neck. Redis is a very VERY fast, in memory cache. By being in memory it never writes to disk so it won’t incur the overheard that we see today. It’s also very lightweight handling many transactions without stressing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/0*8PTho0rtjfkKBCOQ.png" /></figure><p>The switch to Redis as a centralized cache for sessions has done two things. First, no more session drops! If you don’t visit the site in two days from the same device, you’ll have to log in again, but that’s because we don’t want sessions staying around too long. Secondly, the average response time from the backend has gone from over 500ms on average to under 15ms! This means we can process more requests a second without stressing the servers or having to scale up.</p><p><em>Originally published at </em><a href="http://blog.silph.io/2016/07/23/saving-sessions-and-disks/"><em>blog.silph.io</em></a><em> on July 23, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775a8f5ddcfa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-silph-road/saving-user-sessions-and-our-disks-775a8f5ddcfa">Saving user sessions (and our disks)</a> was originally published in <a href="https://medium.com/the-silph-road">The Silph Road</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CDN, CDN, CDN!]]></title>
            <link>https://medium.com/the-silph-road/cdn-cdn-cdn-c44503642e89?source=rss----9845ace5d2b6---4</link>
            <guid isPermaLink="false">https://medium.com/p/c44503642e89</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Marco Ceppi]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 12:58:21 GMT</pubDate>
            <atom:updated>2017-03-19T14:11:54.377Z</atom:updated>
            <content:encoded><![CDATA[<p>Based on the <a href="http://blog.silph.io/2016/07/16/insights-with-datadog/">data we’re getting from Datadog</a>, it’s clear disk utilization is the biggest boon in our deployment. One thing that hits the disk a lot is the sites assets: images, javascript, css, etc. On average, each page has nearly 200 assets to load — if you can imagine, each pokemon image means a minimum of 151 images ;).</p><p>In order to prepare for invites going out, we wanted to make sure we could handle the load without having to scale more. One way to help offload stress of each image, css, and javascript request hitting the server is to put these static assets into a Content Delivery Network, or CDN.</p><p>A CDN is a means to distribute files from multiple locations around the world. If you imagine the following diagram is how things work today:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*OvjqtBSzPSCKiIjV.png" /><figcaption>The world</figcaption></figure><p>As you can imagine, if you’re on the eastern seaboard of the United States, getting images to load from the site is a lot faster than if you connected from India. This is because there’s less infrastructure you have to travel through from New York to Washington DC than from India. What a CDN offers is the ability to place our static content closer to you! Most CDNs have multiple points of presence, or POPs, where they replicate and store content.</p><p>What that means is, when you visit a website, instead of going all the way to the Washington, DC area, you’re actually getting the content from a POP that’s closest to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*YOnOoEjOTYMqbwbk.png" /><figcaption>Simplified view of what a common CDN POP map looks like</figcaption></figure><p>Now, if you’re in India, the content will load just as fast as if you were accessing it from New York. For our CDN I decided to stick with Amazon and use their “CloudFront” service.</p><p>To enable this was pretty easy, I just uploaded the content to an S3 bucket then told CloudFront to syndicate that bucket. The hardest part was getting the content to serve from that address. Typically we would change these URLs in the application, but we didn’t quite have time to hunt this down, build this in, then deploy it. So the change as actually made at the loadbalancer level by adding the following to the frontend definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99a8deff70a536c013c85ac2da1818d8/href">https://medium.com/media/99a8deff70a536c013c85ac2da1818d8/href</a></iframe><p>While simple, this change basically says if any request coming into the loadbalancer starts with /img then we redirect that to the CDN URL instead. This means <a href="https://thesil/%0Aphroad.com/img/pokemon/animated/blastoise.gif">thesilphroad.com/img/pokemon/animated/blastoise.gif</a> gets redirected to <a href="https://d24wnu4kg3mkno.cloudfront.net/img/pokemon/animated/blastoise.gif">d24wnu4kg3mkno.cloudfront.net/img/pokemon/animated/blastoise.gif</a>. That URL will point to a different POP depending on where you’re physically located. In the coming weeks we’ll make this URL configurable in the codebase so that instead of having to go ALL the way to DC just to get repointed somewhere else, you’ll go straight to that URL from the start. This will help lower the stress on the loadbalancer and improve performance for everyone visiting the site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5AJRwj_JCN2W4LjV.png" /></figure><p>This is what the cut over looks like. Around 1:15 is when we switched over to the CDN, backend traffic is way down. However, frontend sessions have jumped up. This is because we’re handling the rewrite at the to the CDN. Either way, the goal is accomplished by lowering the stress on the servers disks and increase the sites responsiveness by having assets load faster for users.</p><p><em>Originally published at </em><a href="http://blog.silph.io/2016/07/18/CDN-CDN-CDN/"><em>blog.silph.io</em></a><em> on July 18, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c44503642e89" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-silph-road/cdn-cdn-cdn-c44503642e89">CDN, CDN, CDN!</a> was originally published in <a href="https://medium.com/the-silph-road">The Silph Road</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data driven decisions with Datadog]]></title>
            <link>https://medium.com/the-silph-road/data-driven-decisions-with-datadog-d089380e3790?source=rss----9845ace5d2b6---4</link>
            <guid isPermaLink="false">https://medium.com/p/d089380e3790</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[datadog]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ubuntu]]></category>
            <dc:creator><![CDATA[Marco Ceppi]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 12:47:37 GMT</pubDate>
            <atom:updated>2017-03-19T12:47:36.974Z</atom:updated>
            <content:encoded><![CDATA[<p>With a site this size and a team this small knowing where to invest time is crucial. We’ve been benchmarking the new infrastructure for the past few days and the numbers aren’t quite what we’d like to see. Since we’re moving quick I don’t quite have time to setup things like Prometheus, Nagios, or other monitoring tools. I also don’t want to have to manage more infrastructure than we already are. That’s what ultimately lead me to the choice of <a href="https://datadoghq.com/">Datadog</a> a tool I’ve seen demos for at a few conferences but never really had a reason to use.</p><p>Getting going with Datadog was way easier than I anticipated. I decided to play around with it first on a single machine. I broke the cardinal rule of juju deployments and ssh’d onto a unit of silph-road and <a href="https://app.datadoghq.com/account/settings#agent/ubuntu">installed datadog</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58475cfe2cbaf589ed51733c1837f061/href">https://medium.com/media/58475cfe2cbaf589ed51733c1837f061/href</a></iframe><p>They have a one-liner, but curl | bash is never a real good install method. Above is the “manual” installation steps which really aren’t that bad.</p><p>Once the agent was installed, data showed up instantly. Something I like a lot is how integrations work. There are a lot of integrations out of the box, with a quick tweak to some config files I was able to get metric data from NGINX and PHP-FPM streaming in along-side machine metrics. There’s also a series of dashboards that make visualizing data really sweet. So, I quickly pieced together a Datadog agent charm and bolted it onto all of the applications in the deployment.</p><p>From there, I held my breath as data started pouring in. I know there are still problem areas, people not getting pages to load and the app preforming sluggishly under load. All of these are a problematic for people using the app, especially considering the number of mobile users. I used the default HAProxy dashboard and NGINX dashboard and started creating our operational dashboard to help watch for problem areas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cN2wlJDxc0QAm5vJ.png" /></figure><p>Diving right in, one thing is clear: there’s is a lot of traffic hitting the loadbalancer, and a lot of traffic drilling down to NGINX. At first I figured this is just PHP being PHP, slow and arduous. After building out a few dashboards it became clear that while PHP was the bottle neck, it wasn’t the sole bottle neck. In fact the thing most in common was slow response times from NGINX directly, returning things like .png and .js files. As well as PHP taking a long time to load. What was actually happneing was long IO wait times as NGINX was reading from disk and PHP was reading and writing session data to disk.</p><p>It’s clear that EBS volumes in Amazon are not up to the task. We’re formulating plans on how to alleviate the stress to the disks on Amazon. One thing is clear, adding more units of silph-road won’t scale for our budget and we’re going to have be smarter about the resources we have. Now that we have metrics, stream real-time data, we can be much smarter with where we focus our time. From improving the charms and infrastructure, to tuning the application, to produce a much more cost and performance efficient site that loads quick and reliable.</p><p>In an attempt to further open our operations we’ve setup a public <a href="https://p.datadoghq.com/sb/a42d80f38-e1f5b6fc5e?tv_mode=true">Datadog dashboard</a> which is our starting point for monitoring the infrastructure.</p><p><em>Originally published at </em><a href="http://blog.silph.io/2016/07/16/insights-with-datadog/"><em>blog.silph.io</em></a><em> on July 16, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d089380e3790" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-silph-road/data-driven-decisions-with-datadog-d089380e3790">Data driven decisions with Datadog</a> was originally published in <a href="https://medium.com/the-silph-road">The Silph Road</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reusing operational knowledge]]></title>
            <link>https://medium.com/the-silph-road/reusing-operational-knowledge-879a95beafa?source=rss----9845ace5d2b6---4</link>
            <guid isPermaLink="false">https://medium.com/p/879a95beafa</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Marco Ceppi]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 01:58:03 GMT</pubDate>
            <atom:updated>2017-03-19T01:58:02.883Z</atom:updated>
            <content:encoded><![CDATA[<p>The first thing after joining was to start <a href="http://blog.silph.io/2016/07/14/scaling-up-not-out/">encapsulating the deployment of Silph Road as repeatable code</a>. To maximize flexibility, we use charms written in Python to avoid DSL lockin and allow for more contributions. Since we’re using NGINX and PHP-FPM, we leverage existing charm layers for these to just focus on what it takes to deploy the application and not reinvent every piece of solution. I know what follows may seem like a lot, after all it’s just shy of 100 lines of Python code and some metadata, but this is the basis for all the magic that happens in the deployment. It’s how we can scale elastically while still only being volunteers in the project of this size.</p><p>Before even getting that far though, I needed to figure out exactly how to setup the site. For this, I used LXD. For those not familiar, LXD gives you the equivalent of a virtual machine but without the VM overhead. It’s very similar to the primitives that you’d get from another hypervisor — like VirtualBox — but they are very lightweight. It’s also a great way to emulate the production environment without having to pay for more machines in a cloud. I downloaded the code to ~/Projects/silph/web-app and launched a few containers:</p><pre>lxc launch ubuntu:16.04 silph-web lxc config device add silph-web source-code disk source=/home/marco/Projects/silph path=/srv/silph</pre><p>This creates a fresh Ubuntu 16.04 cloud images and then maps my code directory into the container under /srv/silph. Now you can view the containers using lxc list, access the container with either lxc exec silph-web bash or just ssh ubuntu@[container-ip]. Once in I was able to install NGINX, php-fpm, then spent a few hours installing dependancies, tweaking configuration files, and validating the setup.</p><p>The next bits are pretty technical, if you’re adverse to code you might want to skip the next few paragraphs. Once you have a plan for execution it time to dig in. Charms are pretty straight forward and typically have the following directory structure:</p><pre>. <br>├── config.yaml       # configuration that can be tweaked at deploy<br>├── icon.svg          # icon to make things look pretty<br>├── layer.yaml        # build-time definitions and configuration<br>├── metadata.yaml     # describes charm meta and integrations<br>└── reactive<br>    └── silph_road.py # deployment logic</pre><p>We’ll start with the metadata.yaml, this file is mostly just human-readable fluff, but it does also describe how this charm connects with other deployed components. This is important as we’ll need to integrate with a MySQL server as well as a load balancer.</p><pre>name: silph-road<br>summary: Deploy thesilphroad.com<br>maintainer: Marco Ceppi &lt;marco@ceppi.net&gt;<br>description: |<br>  Silph Road web app<br>provides:<br>  website:<br>    interface: http<br>requires:<br>  database:<br>    interface: mysql</pre><p>Skipping the top half, the key takeaways are the requires and provides sections. This describes what things The Silph Road consumes and provides, mainly being it consumes a MySQL compatible connection and provides an HTTP compatible endpoint. By declaring these two bits Juju will be able to connect this to the <a href="https://jujucharms.com/mariadb/">MariaDB</a> and <a href="https://jujucharms.com/haproxy/">HAProxy</a> charms.</p><p>Just declaring this bit of data isn’t everything though, we’ll also need to declare the other layers we need compiled into the charm. There are two types of layers: a charm layer and an interface layer. Since we’re declaring support for both mysql and http we’ll need to include those interface layers as well as php-fpm and nginx charm layers as we build on top of that technology. Here’s the following layer.yaml file:</p><pre>includes:<br> - &#39;layer:basic&#39;<br> - &#39;layer:nginx&#39;<br> - &#39;layer:php-fpm&#39;<br> - &#39;interface:mysql&#39;<br> - &#39;interface:http&#39;<br>options:<br>  php-fpm:<br>    packages: [gd, mysql, imagick, mcrypt, zip, gd, geoip]</pre><p>Breaking this down further, we declare a set of layers we need to build upon in order to get the Silph Road app working: basic, nginx, php-fpm. Basic is essentially a given, it’s the scaffolding that makes charm layers work. NGINX and php-fpm are the two other components that need to be installed on each Silph Road app machine in order for the site to work properly; we’ll glue these components together in the next section.</p><p>The next two are the interface declarations. These declarations make sure the libraries for these connections get compiled into the charm. They facilitate the implementation of the communication layer between charms. In this case, by declaring the MySQL interface we’ll be able to get MySQL credentials from a charm which provides the MySQL interface. This allows us to automate deployments and scale without having to hand craft configuration files for each machine.</p><p>Finally, the reactive file! This is the heart of the automation of the deployment. In it, describes the instruction set on not only how to install the application, but how to maintain the application over time. While I’m using Python here, other languages are supported. I’ll show the end result of the file and break down each chunk:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d23d171420ae873476909ebe0398101/href">https://medium.com/media/7d23d171420ae873476909ebe0398101/href</a></iframe><p>Here’s that 100 lines of Python code. To get a few logistics out of the way, and of those not familiar with Python. The reactive system provides a means of when you can set and remove flags then declare what code to execute whenever a set of flags match. To declare which set of code gets executed when, we use Python decorators which are all the lines prefixed with @. In the reactive framework @when and @when_not are equivalent to true or false. Multiple decorators stacked over a method are evaluated with the AND operator. So @when(&#39;hello&#39;) and a @when_not(&#39;world&#39;) means whenever the “hello” flag is set but the “world” flag isn’t then the method it’s decorating will be executed.</p><p>Remember when we included layer:php-fpm and layer:nginx? If you notice a few flags aren’t explicitly set in the above python file yet we’re responding to them. This is because each layer included has it’s own reactive python file which is compiled into the charm at build time. Each of these reactive files have their own set of declarations that are globally accessible. This means each layer will run through it’s set of steps to install the bits it needs. All we need to do is react to the php.ready and nginx.available states which are set from each layer respectively.</p><pre>@when(&#39;php.ready&#39;)<br>@when_not(&#39;silph-road.installed&#39;)<br><strong>def</strong> <strong>install_thesilphroad</strong>():<br>    web_path <strong>=</strong> &#39;/srv/web&#39;<br><br>    git<strong>.</strong>clone(config()<strong>.</strong>get(&#39;source&#39;), web_path)<br><br>    create_paths <strong>=</strong> {<br>        &#39;app/tmp/cache/pokedex_cache&#39;: 0o777,<br>        &#39;app/tmp/cache/persistent&#39;: 0o777,<br>        &#39;app/tmp/cache/models&#39;: 0o777,<br>        &#39;app/tmp/logs&#39;: 0o777,<br>        &#39;app/webroot/img/user-verification-photos&#39;: 0o777,<br>    }<br><br>    <strong>for</strong> path, perm <strong>in</strong> create_paths<strong>.</strong>items():<br>        os<strong>.</strong>makedirs(os<strong>.</strong>path<strong>.</strong>join(web_path, path), perm)<br><br>    chownr(web_path, &#39;www-data&#39;, &#39;www-data&#39;)<br>    set_flag(&#39;silph-road.installed&#39;)</pre><p>The above chunk of code is the first declaration in the file. It is also the one that does most the heavy lifting for the charm. It’s triggered whenever the php.ready flag is set and silph-road.installed flag isn’t set. First we clone the source code repo which is declared as a configuration on the charm. Next, we create the additional file paths which aren’t in the source code repo but are needed in order for the app to run. Finally we make sure the source code is owned by the right user before setting the silph-road.installed state.</p><pre>@when(&#39;config.changed.source&#39;)<br><strong>def</strong> <strong>update_cfg</strong>():<br>    remove_flag(&#39;silph-road.installed&#39;)<br>    remove_flag(&#39;silph-road.ready&#39;)</pre><p>This is a pretty simple hack, whenever the source config key is changed, we remove the two main flags so that it runs through the installation again. Since each method is idempotent and the git.clone() method will run a git pull if the source directory exists it’s a super easy way to get changes in the repo propagated. In the future I expect we’ll grow this out to handle migrations in data schema, for now there’s not a need for this.</p><pre>@when(&#39;nginx.available&#39;)<br>@when(&#39;silph-road.installed&#39;)<br>@when_not(&#39;silph-road.nginx.ready&#39;)<br><strong>def</strong> <strong>setup_vhost</strong>():<br>    nginx<strong>.</strong>configure_site(<br>        &#39;silphroad&#39;,<br>        &#39;silphroad-vhost.conf&#39;,<br>        socket<strong>=</strong>php<strong>.</strong>socket(),<br>    )<br><br>    service_restart(&#39;nginx&#39;)<br>    set_flag(&#39;silph-road.nginx.ready&#39;)</pre><p>The next bit here glues up the NGINX configuration file for our specific site. Not shown in the tree above is a templates directory which has a silphroad-vhost.conf. The virtualhost configuration file isn’t really all that interesting, it just sets up where the root directory is and glues the PHP-FPM socker/address to the reverse proxy. After rendering the configuration, we’ll restart NGINX and set a new flag to avoid creating an NGINX configuration file over and over again.</p><pre>@when(&#39;silph-road.installed&#39;)<br>@when(&#39;database.available&#39;)<br>@when_not(&#39;silph-road.db.ready&#39;)<br><strong>def</strong> <strong>configure_db</strong>(db):<br>    ctx <strong>=</strong> {&#39;database&#39;: db}<br><br>    render(source<strong>=</strong>&#39;database.php.j2&#39;,<br>           target<strong>=</strong>&#39;/srv/web/app/Config/database.php&#39;,<br>           owner<strong>=</strong>&#39;www-data&#39;,<br>           group<strong>=</strong>&#39;www-data&#39;,<br>           perms<strong>=</strong>0o640,<br>           context<strong>=</strong>ctx<br>    )<br><br>    set_flag(&#39;silph-road.db.ready&#39;)</pre><p>This block is similar to the NGINX one above, but is unique because it executes whenever the database relation is created. This flag exists because we included both the database relationship with the mysql interface and the mysql interface layer. These factors combined make it so when you deploy a MySQL compatible charm and create a relation between it and another charm, the database charm will create a set of credentials and transmit them directly to our charm.</p><p>The mysql interface layer collects, validates, then raises the database.available flag. Since interface layers are special, they pass a context to the method we execute with a reference to the data from that relationship. db will actually have a hostname, port, user, password, and database keys set. The render method is a shortcut to a Jinja2 templating library and allow us to have a file in templates named database.php.j2 which looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e109b17b97f07f89fc6418709a765dfe/href">https://medium.com/media/e109b17b97f07f89fc6418709a765dfe/href</a></iframe><p>Now we can dynamically create our database configuration without having to manually munge any files! Finally, we have the next two methods.</p><pre>@when(&#39;silph-road.nginx.ready&#39;)<br>@when(&#39;silph-road.db.ready&#39;)<br>@when_not(&#39;silph-road.ready&#39;)<br><strong>def</strong> <strong>ready_freddie</strong>():<br>    open_port(80)<br>    status_set(&#39;active&#39;, &#39;ready&#39;)<br>    set_flag(&#39;silph-road.ready&#39;)<br><br><br>@when(&#39;silph-road.ready&#39;)<br>@when(&#39;website.available&#39;)<br><strong>def</strong> <strong>send_port</strong>(http):<br>    http<strong>.</strong>configure(80)</pre><p>The first one works to just aggregate all the previous states to make sure dependencies are satisfied. In this case we need to make sure nginx and the database are ready. Once that’s done, we tell Juju to open port 80, set the status of the charm to active, and create the silph-road.ready flag. The second method glues the last layer and relationship we creatd. If you recall we have a relationship called website which implements the http interface and we included interface:http - this is the library that implements the communication protocol.</p><p>Unlike the mysql interface, which provides us a mysql endpoint we’re providing an http endpoint. As such, we need to configure the relationship so that applicaiton consuming our http endpoint get the proper configuration. For the HTTP interface, this is as simple as providing the portname for our http server (the interface layer will provide the proper hostname, etc). So when silph-road.ready and website.available we’ll take the context passed as a parameter and relay our port through it.</p><p>So why go through all this trouble? After all we’re fighting against an already over-provisioned instance — speed is of the essence. One of the biggest time sucks I’ve found is when you create bespoke, snowflake, infrastructure. It’s fragile, brittle, and typically leads to problems down the road.</p><p>By making things repeatable and leveraging constructs like Juju and Charms it makes our infrastructure not only repeatable, but also portable. Deploying The Silph Road takes just a few minutes and looks something like this:</p><pre>charm build ~/silph.co/silph-road        <em># compile code into a charm</em><br>juju bootstrap silph.io-prod0            <em># create a juju controller</em><br>juju deploy mariadb                      <em># deploy our MySQL server</em><br>juju deploy haproxy                      <em># our loadbalancer</em><br>juju deploy ~/silph.co/builds/silph-road <em># deploy the compiled charm</em><br>juju add-relation haproxy silph-road     <em># connect haproxy</em><br>juju add-relation mariadb silph-road     <em># connect mariadb</em><br>juju add-unit -n3 silph-road             <em># start scaling out!</em></pre><p>I don’t expect this will be the final version of this charm. It will certainly take some tweaking as we venture further into the deployment. Making patches, however, is as easy as edit layer, charm build, juju upgrade-charm!</p><p><em>Originally published at </em><a href="http://blog.silph.io/2016/07/16/encapsulating-ops-knowledge/"><em>blog.silph.io</em></a><em> on July 16, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=879a95beafa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-silph-road/reusing-operational-knowledge-879a95beafa">Reusing operational knowledge</a> was originally published in <a href="https://medium.com/the-silph-road">The Silph Road</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling out, not up]]></title>
            <link>https://medium.com/the-silph-road/scaling-out-not-up-427d6cdc6fa6?source=rss----9845ace5d2b6---4</link>
            <guid isPermaLink="false">https://medium.com/p/427d6cdc6fa6</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[pokémon-go]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Marco Ceppi]]></dc:creator>
            <pubDate>Sun, 19 Mar 2017 00:47:33 GMT</pubDate>
            <atom:updated>2017-03-19T00:47:33.254Z</atom:updated>
            <content:encoded><![CDATA[<p>Joining The Silph Road meant a shift in architecture. The platform’s hosted on Amazon’s Cloud where the application, the Apache web server, and MySQL lived on a single machine. This isn’t a bad design, by any means, and is quite common for “LAMP” (Linux, Apache, MySQL, PHP). There is, however, trade-offs to this design. The biggest of which is the limitation of scale, which is what we hit during the first code launch.</p><p>When traffic hits, the load on a single server becomes clear. Apache, PHP, and MySQL are all fighting for machine resources so the only way forward in this model is up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/0*L4CDNZho0rvlHzVE.png" /></figure><p>This was the Reddit post that caught my attention. There comes a point where you can’t physically get a bigger sized machine (or VM in a cloud). At that point, you need to start considering a scale-out architecture as a path to handling more requests. The general principle of scale out: instead of one machine doing everything, you have many smaller machines processing requests. These machines typically get grouped into multiple tiers. These tiers each function towards a single goal. We separated each concern and created two tiers: A database tier and application tier. Since we have more than one machine in the application tier we need a way to route requests properly. To do so we’ll use HAProxy, a load balancer, designed to route and balance traffic to one or more machines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*4M7EVMBDQgd10pHR.png" /></figure><p>Additional to this separation, there were also a few product changes. Where before the architecture was Amazon Linux, Apache2, MySQL, and PHP; the new architecture is Ubuntu, NGINX, MariaDB, PHP-FPM, PHP. Aside from moving to a more updated and secure Linux, the other choices were more personal. I have much more experience with NGINX and PHP-FPM than Apache and mod-php. MariaDB has tested to be a more performant replacement for MySQL.</p><p>All this sounds great, but how we put this in place isn’t a trivial exercise. With ample time tools can be evaluated and experimented with. However, we’re scaling under load and under fire and can’t afford this grace period. This is why we’re using Charms and Juju to drive our infrastructure.</p><p>Charms themselves are the encapsulation of the operational logic for each piece of software. We don’t have time to become experts at scale for each component: MySQL, HAProxy, NGINX, etc. What charms provide is a curated, cloud-optimized, cloud-agnostic, and reusable set of expertise. This means we’re not locked into choices we make now and can scale/change components, or clouds, at any time.</p><p><em>Originally published at </em><a href="http://blog.silph.io/2016/07/14/scaling-up-not-out/"><em>blog.silph.io</em></a><em> on July 14, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=427d6cdc6fa6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-silph-road/scaling-out-not-up-427d6cdc6fa6">Scaling out, not up</a> was originally published in <a href="https://medium.com/the-silph-road">The Silph Road</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>