<?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 Karuhanga Lincoln on Medium]]></title>
        <description><![CDATA[Stories by Karuhanga Lincoln on Medium]]></description>
        <link>https://medium.com/@karuhanga?source=rss-28289fc41654------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OqR48shTdvOjK6Cv7_ZPDA.png</url>
            <title>Stories by Karuhanga Lincoln on Medium</title>
            <link>https://medium.com/@karuhanga?source=rss-28289fc41654------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:03:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karuhanga/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[Of Data, Storage and Abstractions you thought you could depend on]]></title>
            <link>https://medium.com/@karuhanga/of-data-storage-and-abstractions-you-thought-you-could-depend-on-e8275e325826?source=rss-28289fc41654------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8275e325826</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databases-big-data]]></category>
            <dc:creator><![CDATA[Karuhanga Lincoln]]></dc:creator>
            <pubDate>Wed, 10 May 2023 08:40:49 GMT</pubDate>
            <atom:updated>2023-05-10T08:40:49.990Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preamble</h3><h4>Audience</h4><p>Junior to mid-level engineers will probably learn a few new things, more experienced engineers might find this a proper refresher on the fundamentals.</p><h4>Goal</h4><p>Do a quick skip through, a-la hoping on rocks in a pond and if you’d like to flip a rock a find out what’s underneath, feel free to.</p><h4>Tldr</h4><ul><li>Starting to write this and stumbled across ‘<a href="https://link.medium.com/EAsBdo2sK6">Things I Wished More Developers Knew About Databases</a>’- Jaana Dogan which is a really good read.</li></ul><p><strong><em>Let’s dive in, shall we?<br></em></strong><em>note to self: start off with some insightful story of how humans got to the point where they noticed they needed to physically record things down so that they could remember them and agree on what they’d previously agreed upon.</em></p><h3><em>Building a database</em></h3><p>It’s not that hard to connect the dots from that point to a point where I presume someone noticed you could find things faster if you kept them in some order or agreed some rocks were used to record things about money and others tallies on who made the funniest jokes. Then paper, then books, then finally computers keeping things on paper and finally disk.</p><h4>Writing Data</h4><p>So let’s restart. Your task is to keep things on disk. The level of abstraction we’re working with here are files and disks and we’re only going up from here. Hopefully, you’d quickly figure out you needed some kind of <em>database</em>. The simplest would be one where you’d store things by key and value, right? <em>student_1: {name=bob, age=14}.</em></p><p>Is actually not as difficult as one might think, you’d just append this data to an ordinary text file when writing. Reading would mean running through all the lines and finding your matching key. When you got lots of data you’d start looking at things like splitting the file because it became too big, getting rid of unnecessary entries- compaction, combining the smaller files after compaction and building a separate directory that allows direct jumps to a specific piece of data without having to go through all the data- indexing. So far, we’ve done an append only thing, meaning writing with a similar key would just add it to the end ergo we only care about the most recent write for conflicting keys, effectively an update. You can derive a delete from an update by updating with a special/ <em>tombstone</em> value.</p><p>We’re obviously glossing over a lot here, right? This is a terrible file format for things like compression, we haven’t talked about crashes(lost data, partial writes) and how you’d recover from that, concurrency and a few other things.</p><p>Indulge me for a bit though and let’s continue glossing on for a while. How would you index this?</p><ul><li>You might hash the keys(<em>key_value → some_unique_number</em>). We know that finding 50 when you have numbers 1–100 is easy, just look in the middle. You’d then create an in-memory a table of hashes → where your entry is. And yes, this is how several production systems work, Bitcask in Riak for example. Obviously, this means your hashed keys should be able to fit in memory, and doing things over key ranges is painful(keys are hashed, remember?).<br>[We can take this further and talk about in-memory databases; VoltDB, MemSQL for example that give you great performance boosts if you have enough RAM to hold **all** your data.]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*5rmLL5lh_xYCVwL8ADcr8g.png" /><figcaption>Storing a log of key-value pairs in a CSV-like format, indexed with an in- memory hash map.</figcaption></figure><ul><li><strong>S</strong>orted <strong>S</strong>tring <strong>Tables</strong> and <strong>L</strong>og <strong>S</strong>tructured <strong>M</strong>emory-<strong>Tree</strong>s: The principle here is simple; keep data sorted by key in memory(LSMTree), using a red-black tree for example and write to a file on disk periodically, with the rule that each file contain only a single instance of a unique key with the keys in sorted order and the value coming from an aggregate/ simply the most recent write. Finding a key here means you search the in-memory structure and then the files, from the most recent(each file is sorted, so indexing shouldn’t be expensive, for example using the hashing technique above). We could also compact and merge files from time to time. Examples here are Level and Rocks DB. Lucene uses a similar(slightly more complicated obviously)).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*wfkfP9XZYOmGNkr6qEdl5A.png" /><figcaption>Merging several SSTable segments, retaining only the most recent value for each key.</figcaption></figure><ul><li>B-trees: Elegant one this one. The principle here is; since hashing gives you effective keys over some range, can we build indices that keep access to the data efficient enough? Something on the magnitude of <em>logn</em>? A four-level tree of 4 KB pages with a branching factor of 500 can store up to 256 TB. There’s several additional things to think about here primarily around reliability. A key thing to have is a write ahead log to help with recovery if something bad happens in the middle of an operation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*6wL_uU6RdHx_XMR7oiycLQ.png" /><figcaption>Looking up a key using a B-tree index.</figcaption></figure><p>The above structures would make up what one might call a primary index, for example indexing over a primary key. Indexing needs don’t stop here though, and other use cases arise;</p><ul><li>Secondary indices- The key difference here is these indices don’t have to be unique and we can have as many as we need, keeping in mind that each additional index has a performance penalty i.e when making any change to the database, we’ll have to update the indices to reflect the new value as well.</li><li>Multi column indices- Uhm, indices over multiple columns(concatenated indices for example).</li><li>Full-text search and fuzzy indices- Search over the entirety of the contents of a document, making allowances for things like synonyms.</li></ul><p>The last use case is a good segue into something you should be starting to notice. The use cases are very diverse and particular systems can be optimized to focus on particular ones. Nowhere is this more clear than the distinction between online transaction processing vs analytics systems which differ in;</p><ul><li>Small reads vs aggregates</li><li>Random access vs bulk operations</li><li>User facing vs analyst facing</li><li>Latency expectations- real-time vs historical</li><li>GBs vs TBs</li><li>Use case/ service focused vs <a href="https://en.wikipedia.org/wiki/Star_schema">star</a> and snowflake schema</li><li>Row vs column oriented storage which makes use of the fact that data in a particular column will always have a similar format, making it easier to do aggregates and compression over it(You can think of this as instead of having one list of objects, having <em>n</em> lists of attributes)</li></ul><p>Diving further into use cases, you’ll quickly notice there’s still a diverse set of applications, even within an organization, generating different kinds of data. I cannot exaggerate how important having a data model that maps cleanly to your type of data and the way you conceptually think about it is.</p><ul><li>Relational(PostgreSQL, for example)- data is stored in row oriented relations and each entry makes up a new row.</li><li>Document(MongoDB, for example)- each entry is a self contained ‘document’ containing all the data that makes it up.</li><li>Graph/ graph-like data models(<a href="https://docs.racket-lang.org/datalog/">Datalog</a>, for example) where the concept of entries tying to each other in a web-like manner is represented in the data model with edges and vertices being first class concepts, useful for representing things like social graphs.</li></ul><p>Many factors will go into one picking one model over another, for example the relational model is more friendly to normalization and foreign keys between data, the document model allows one to write data without the constraints of a fixed schema, effectively determining the schema on read and the graph model makes it easier to reason through queries with graph structured data. There’s been a convergence towards a compromise among these models overtime and this short summary <strong>does not</strong> touch on numerous predecessors whose ideas shaped where we are today.</p><h4>Reading Data</h4><p>There’s obviously no point storing data if you won’t try to access it later, and this necessitates some kind of way for accessing the data- a <em>query</em> language if you will. These languages can either be imperative, i.e lay out each step of how you’d like to find the data, or declarative, i.e tell us what you want and we’ll figure out how best to get it to you. Declarative languages, like SQL and CSS lend themselves better to things like parallelization and free-lunch type improvements.</p><p>To give you an example of how key having an appropriate data model and query language can be(I admit this is a bit of a contrived example because we could have modeled/ queried for locations a little bit better saving us from the recursive query to get to the country level, but I think it makes the point), here’s an example of a query to find people who emigrated from the US to Europe in SQL over a relational database vs The Cypher Query Language over a graph database;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*eRchuy0eQJyOuBBANYDUpQ.png" /><figcaption>SQL over a relational database</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*pIFqYSqX7TavGGAGvfBYkQ.png" /><figcaption>The Cypher Query Language over a graph database</figcaption></figure><p>The details of the query are not relevant. The point here is to give you an idea of the gain you get from understanding your data and modelling it appropriately.</p><h3>Of Production Grade Systems</h3><p>Let’s take a step back and return to what we assume, or should be assuming for that matter, we get from our data stores(if you don’t think about these things when making a data store decision, perhaps you should consider doing so going forward);</p><ul><li>Reliability- we’ll call this ‘continuing to work correctly’. Details here would go into ‘after what?’ After user error, encountering expected load, expected and unexpected abuse, software errors, hardware faults.</li><li>Scalability- Can we handle an increase in <em>load</em> gracefully? How would its performance change? The bottom line here is you have to look at a distribution of throughput(how many requests are you handling in time <em>t</em>), latency(time request is waiting to be handled) and response times(total time from the user’s perspective) both in terms of median and what the worst percentiles look like. This leads us down the rabbit hole of more finely grained SLAs and SLOs.<br>[How do we describe load? I’ve seen hand wavy definitions like ‘requests per second’, but these are too general and don’t put into context the type of service and how users interact with it. Is the service read or write heavy? Can we have a global cache or is caching localized to the user? Which parts of your application attract the most load? Are all users the same or do some users attract more engagement than others? An excellent example from the book asks how you would read data for a twitter user’s timeline. Would you query on demand for each user? Would create an effective mailbox and send new tweets to this mailbox? Would your approach avoid overwhelming objects belonging to popular users?]</li><li>Maintainability- Simple, evolvable and operable, aka, <em>‘How loudly will you complain about choosing this product on Twitter 2.5, 5, 10 years down the road?’</em></li></ul><p>We typically lay all these out while designing the system and agree on what we want to expect from it. For example, if a meteor crashed with earth, all bets are off!<br>How would you build a so called internet-scale persistence system from scratch? This is one of those things one assumes is <em>solved</em>, mostly because we know it is being done and therefore <em>can</em> be done, despite this knowledge existing in not that many companies.</p><p>Conceptually, you need to;</p><ul><li>store data so you can find it later</li><li>remember data you’ve seen</li><li>remember data you’ve recently seen even faster</li><li>quickly search through piles of data quickly</li><li>crunch large amounts of accumulated data</li><li>send off a message to be handled by someone else</li></ul><h4>Moving data around</h4><p>I’d like to pick up on something I hinted at a little earlier; the diverse use cases and how they drive the design of storage systems. Inevitably, this will lead to a need for the various systems to communicate;</p><ul><li>Two subsystems(services? is that what the kids call it these days?) will need to share data</li><li>One service(see, I’m getting into it) will want to pick information from another service</li><li>Your client facing code will want to make calls to your backend service(s?)</li><li>You’ll want to move data into a more central location to do interesting things with it</li><li>… add a usecase here(there’s a ton)</li></ul><p>There’s several considerations when discussing moving data around, but for now, we’ll focus on how the format/ schema of that data evolves, how data flows between systems and the format on which these diverse systems will agree to use for communication.</p><p><strong><em>How do we move data between systems right now?<br>(Data transfer modes)</em></strong></p><ul><li>Service calls. SOAP, REST, RPC(you’ve probably heard of pain from CORBA and EJB, but new generations of this are making it slightly less painful. gRPC for example has become quite popular). Mostly synchronous, often real-time.</li><li>Asynchronous message passing(some IOT sensor tells us when the temperature changes and doesn’t really wait to hear whether or not we received the message). Typically involve(, fancy term alert:) message brokers(RabbitMRS, ActiveMQ, Apache Kafka etc) which act as buffers and decouple message generation from consumption. Also a good time to mention distributed actors(Akka, Orleans for example). The actor model makes concurrency easier to think through by having units of processing be kicked off by delineated messages allowing the entities doing the processing to not care about other messages and other possible producing or processing entities, saving us having to think about multithreading, orchestration etc etc.</li><li>Via Databases. Obviously databases have protocols for sending an receiving data, but that’s detail that’s handled by one of database clients you’ll use. You typically download a driver specific to your db engine that knows how to handle this logic. We care about this abstraction, just, not right now.</li></ul><p>In this piece, we’ll focus on the application layer of the tcp/ip model. Most of these data formats are used over a protocol like http- we don’t care at this point(yay abstraction).</p><p><strong><em>What does this data look like anyway?<br>(Data transfer formats)</em></strong></p><ul><li>JSON- you know JSON :), XML, Binary Formats(BSON, BJSON, BISON)- the goal here is efficiency. JSON is still quite verbose and these shave off some of that verbosity and hence data size.</li><li>Language specific formats- pickle in Python, Serializable in Java, Marshal in Ruby.</li><li>Thrift, Protocol Buffers(yes, protobuffs)- These are more binary encoding libraries+ formats than just formats. The goal here is efficiency, and in that interest, we define a fixed, possibly evolvable structure and the type of the data allowing us do things like not verbosely send object attribute names every time and compress data more effectively.</li><li>Apache Avro- Same principle as the previous two but with important nuances, like the reader and writer need to have compatible schema since there’s no concept of field tags or names. As in the previous two, the reader and writer need to have a way to agree on the schema of the data(perhaps send it along with the data, have a version number with each record or negotiate a version number before transmitting the data)</li></ul><p>As always, each of these has its trade-offs. Security, ease of dynamic schema generation, for example. Note that this focuses on the data format itself, and not necessarily on <strong>how</strong> it is delivered which was covered in the transfer modes. <em>In theory</em>, you should be able to mix and match the modes and formats depending on you use case.</p><p><strong><em>How does the format in which this data is kept change?(Evolvability)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*VJt3MzOQUferxgm_OgDzfw.png" /><figcaption><em>When an older version of the application updates data previously written by a newer version of the application, data may be lost if you’re not careful.</em></figcaption></figure><p>I like the spreading syntax introduced in JS ES6 because it often allows you to deal with specific attributes of an object’s data without caring about changing/ accidentally dropping other attributes on it. The point I’m trying to make here is you should start taking care that your code does not make assumptions about how an object/ schema will evolve, because it could lead to things like unintentionally dropping fields because of improper forward/ backward compatibility.</p><p>If you’re running an application on a single instance, this is complexity you probably don’t need to worry about nearly all the time. When you start having multiple instances of the same type of service often running different versions and/ or different services, often on blue green deployment schedules, or external services depending on your single instance or an android device somewhere that’s like 5 months behind on updates, you need to start caring about these things.</p><p>A few principles to follow here;</p><ul><li>Your APIs(in general, not just the Rest APIs you are probably more familiar with) should evolve without breaking existing functionality</li><li>Backward compatibility- Newer code can read data written by older code</li><li>Forward compatibility- Older code can read data written by newer code</li></ul><h3>Of Non-Trivial Amounts of Data</h3><p>We began by appending data to a text file and quickly realized there are more efficient ways of storing this data. Something we swept under the rug though was data size. If your service is mature/ popular enough, you’ll eventually get to the point where you can’t depend on a single-node instance of your data store, most probably because;</p><ul><li>you have a sufficiently large amount of traffic and your server might get overwhelmed, leading to slow <em>performance</em> which can quickly cascade into scary failures<br><em>[performance- throughput and latency for reads in this instance- e.g most people scroll through their feed more than tweet]</em></li><li>fault tolerance- you probably don’t want to lose your users’ data because one machine failed</li><li>you can’t have a big enough disk to hold an infinite amount of data</li><li>you might want to keep data as close as possible to your users, think how quickly can the Netflix episode get to me?</li></ul><p>You typically cope with load by scaling vertically(typically heavier compute power) or horizontally(splitting up load either by domain/ service/ functionality or groups of users).</p><h4>Replication</h4><p>Here be dragons, people. The goal here is to make <em>m*n</em> copies of the <em>s</em> size data. Options;</p><ul><li><strong><em>Have a ‘leader’ handle the meat of the writes<br></em></strong>This makes it the source of truth. Followers then <em>copy</em> everything the leader does. PostgreSQL, MySQL, MongoDB, Kafka all have this as an inbuilt feature. Doing this copy now means you’re writing to <em>m</em> data stores instead of one. You might be doing this synchronously/ asynchronously. There’s a lot of tradeoffs here. Read the book! There’s a lot of gold on this there and a number areas of active research.<br>The leader might fail, so you need to be able to handle this gracefully. The <a href="https://en.wikipedia.org/wiki/CAP_theorem"><strong>CAP</strong></a> theorem says you’ll have to sacrifice consistency/ availability under a network partition. You’ll also have to think about what to do when a follower fails(catch up with the writes it missed) and when a leader fails(fail over).<br><em>[what does ‘copy’ mean? It could mean literally repeating everything the leader does(statement based), it could mean following the log of what the leader does(e.g write ahead log shipping, etc) and performing the same operations, it could mean row based replication or it could mean trigger based replication(handled via custom code)]</em></li><li><strong><em>Have multiple leaders</em><br></strong>Typical use case is you have multiple data centers and you choose to write to a leader in one and replicate to leaders in other data centers who then replicate to their respective followers. This can help with improving performance and tolerating failures/ network issues even up to data center levels. Interesting sub cases of this are independent clients all accepting writes, think your calendar on multiple devices and collaborative editing, think google docs.</li><li><strong><em>Leaderless Replication</em><br></strong>Any node accepts writes and either sends them to other nodes or uses a coordinator to help with this. Read and write quorums are are used here to ensure correctness, that is how many nodes do we need to wait to confirm write(w)/ read(r) receipt before we consider it done and dependable?- if some number of your <em>n n</em>odes fail, you’re still safe if <em>w </em>+ <em>r &gt; n</em>. While you can blindly stick to some quorum, you’ll get better performance/ availability if you relax it a little(sloppy quorums), but with inconsistency risks. Once again, tradeoffs.</li></ul><p><strong><em>The Dragons<br></em></strong>The following issues exist at the database level and engineers often have to work around them, e.g using distributed transactions to enforce certain guarantees across the system, so that services and entire systems can provide stronger guarantees to users/consumers that these.</p><p><em>Problems with Replication Lag</em><strong><br></strong>If you choose to replicate your database asynchronously, you have to deal with the fact that writes might get to master but not be at the followers yet. This is another of those situations where we created a bit more of complexity by solving a different problem. We have to go ahead and solve this though. Several levels of problems come out of this and we can choose to solve up to some level(tradeoffs, remember?)</p><ul><li>Reading your own writes(write to master, read a lagging follower). Solving this gets us to read after write consistency. If I write something I need to see it the next time I try to read. We can do this by reading something from the leader if we know we just wrote it.</li><li>Monotonic Reads(things moving back in time. I hit follower 1 the first time I read, then follower 2 the other time. 2 lagging behind 1.). We can solve this by always reading from the same node.</li><li>Consistent prefix reads- If write A happens before B, that should be the order in which I read them, despite the fact that the writes may have reached different followers at different times, for example, due to variable network delays a user might see a post asking the question after they’ve seen the answer out of context. We can try to solve this by keeping track of what reads logically ‘come before’ others and keeping it that way. (to do, chapter 6)</li></ul><p><em>Write Conflicts</em><strong><br></strong>If you go with multi leader replication, you’ll also have think about write conflicts. Think a git conflict like situation with writes happening at the <em>same time </em>at two different masters. Solving this is basically the same approach you take to solve code versioning conflicts, that is keep one based on some criteria for example picking the most oldest/ most recent one, have the writes merged or store all the values for the conflict to be resolved later, by a client on read. Of course if we can avoid having them at all, we’d like that, so clients can try to the same leader if possible, for example make editing a particular user’s data sticky to a node.<br>[There is no time in distributed systems(well there is, but we’ll touch on that nuance later). Anyway <em>same time</em> means the two writes didn’t know about each other at the time of writing]<br>[I’ve always been fascinated by how <a href="https://stackoverflow.com/a/36366174">conflict resolution in google docs</a> works.]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*zB2wHYTTNSu4Os3lvtlWtA.png" /><figcaption>Capturing causal dependencies between two clients concurrently editing a shopping cart.</figcaption></figure><p>As you can see, writes depend on previous versions and indicate on which versions they are based, otherwise, we’ll assume that version was not included in the merge. The picture becomes a little more messy when you include deletes, which are represented by tombstone values, like we saw earlier on.</p><h4>Partitioning</h4><p>In which we split n size data into n/m m-sized pieces(or something like that). Actions that can operate on a single partition are independently executed. It can obviously be combined with replication such that you then replicate each of the shards. We focus on partitioning only in this section.</p><p>You need to decide what data you’d like to store on what nodes, and how large you’d like your nodes to be. Making an incorrect decision can lead to uneven load on your nodes. You could choose to assign records to nodes randomly, but you’d now have to query all nodes to find where a record is when you have its key. You could partition by key ranges, but keys are not necessarily evenly spaced either and you’ll find you need to re-balance partitions as they grow. You’ll still have unexpected hot-spots even after you this though, and you’ll find yourself trying to increase the granularity by which you assign partitions by keys, for example, if your keys are time-based, some minutes might have a lot more hits than others.<br>Partitioning by key hashes is often a good solution as it should give you a uniform distribution. You can then assign partitions ranges of hashes. Doing this though means you lose the nice advantage of key-range partitioning- efficient range queries. MongoDB for example will resort to sending range queries to all shards. Cassandra lets you have a compound primary key and specify how much of that shall be used for the partitioning hash, the rest of the key still supporting a range scan. This can be helpful for performing efficient queries for a specific user’s data for example.<br>[We mentioned hashing, but what works even better here is actually a <a href="https://en.m.wikipedia.org/wiki/Consistent_hashing">consistent hashing</a> algorithm, which helps you when assigning data to partitions as the partition can reliably still be deduced from the hash while still avoiding unnecessary reassignments when the number of partitions change.]</p><p>All this work still does not save you from skewed workloads though, that is keys with significantly more traffic than average.</p><p>Secondary indices unfortunately don’t map to partitions and you’d either have a local index for each shard and query all of them(scatter and gather) or have global indices partitioned by term, which is especially useful for range scans and makes reads more efficient since the entire index is on a single node, at the expense of slower writes.</p><p>Re-balancing is often necessarily and is often done by having many tiny partitions ahead of time such that re-balancing is done by re-assigning partitions to a new node as more are used/ grow larger. A fairly intuitive but terrible approach would be to instead partition by modulo number of nodes, which causes one to have to move a lot of data around when a new node is added/ lost. One should also decide whether or not this re-balancing should be manual or automated.<br>Partitions can also be created dynamically and handled entire by the database and automatically adapts to the data size, especially when partitioning is by key range.<br>When re-balancing happens, we need a way for clients to know where particular data now lives(more generally, this is an example of service discovery), hence the need for co-ordination services like ZooKeeper.</p><h3>Of Those Abstractions[ You’d Think] You Can Depend On</h3><p>Using transactions is one of those things you <em>know</em> but never quite appreciate until it bites you, often when you start handling non-trivial amounts of traffic. Using them then becomes one of those things you’re happy is there but that you just take for granted.</p><p>A typical example of the need for transactions is a bank account credit, debit operation , that is you don’t want to deduct a balance and have a failure before you debit the destination account- a little ironic since banking and reconciliation systems are one of the most common examples of eventual consistency in practice, but for this case, it suffices. This particular instance sounds like a single object transaction, but could easily become a multi-object translation once foreign key references, for example to account holders are introduced.</p><p>You should have heard of the term <strong>ACID</strong> by now, which was for the longest time the hand wavy goal for transactions. NoSQL databases have muddied the waters a little here.<br>I generally think about it in terms of single transaction only properties vs how does this interaction interact with others properties?</p><p><em>Atomicity(</em>single transaction<em>)- </em>It either happened or didn’t.</p><p><em>Consistency(both, really)- </em>In the context of ACID, <em>consistency</em> refers to an application-specific notion of the database being in a “good state.” Which really means, you’d achieve it using other database properties, but it can’t really be defined at database level.</p><p>[<em>Consistency </em>is, unfortunately, terribly overloaded:</p><ul><li>Replica consistency and the issue of eventual <em>consistency</em></li><li><em>Consistent hashing </em>is an approach to partitioning that some systems use for re-balancing</li><li>In the CAP theorem, the word <em>consistency</em> is used to mean linearizability(A happens before B)</li><li>In the context of ACID, <em>consistency</em> refers to an application-specific notion of the database being in a “good state.”]</li></ul><p><em>Durability(</em>single transaction<em>)</em>- Once data has been written, it cannot be lost. What <em>durability</em> means in the age of replication is not universal and you would have to understand to what level your system can guarantee it, that is at what level are all bets off? Power outages? Network partitions? Hard drive failures?</p><h4><em>Isolation(Concurrent transactions should not interfere with each other)</em></h4><p>It’s important to understand what isolation guarantees you get from your databases when you use transactions. These go from the weakest, to the strongest guarantees.</p><p><strong><em>Dirty reads, writes</em><br></strong>Transaction accesses data that has been written, but not yet committed, e.g reading a game’s current score and the scorer’s goal tally while another transaction is done updating the score but still in the middle of updating the goal tally.</p><p><em>Level of isolation that addresses this: Read committed.</em><br>You can only read and overwrite data that has been committed. This could be implemented by locking a row being targeted by a read or write, which is a little inefficient. A better way is to remember both the current value and the new values being set by other transactions and give all other transactions the current value until it is replaced by a write by a committed transaction.</p><p><strong><em>Non repeatable reads/ Read skew</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*amLjHrS7ZU2CbETKsSmVkQ.png" /></figure><p>Transaction accesses the same data multiple times during a transaction, getting back a different result each time because a different transaction updated that data in between the two reads.</p><p><em>Level of isolation that addresses this: Snapshot Isolation(Serializable in Oracle, Repeatable read in PostgreSQL and MySQL)</em><br>The problem here is the second read happens after a commit from a separate transaction and since the old value is replaced after *any* other commit, we end up here. The solution here is having the entire transaction read from an unchanging snapshot of the data. Logically, this implies that we have to expand the versions we keep from earlier to <em>all versions that might still be accessed by active transactions</em>(Multi-version concurrency control(MVCC)). A transaction then ignores data written by transactions with newer transaction ids, and those that were already in progress at the time the transaction started. Indexes are complicated a little here, but I won’t be going into this.<br>[Fun digression: PostgreSQL uses 32-bit integers as transaction ids which is how we can identify what data a transaction should be able to see(ids of completed transactions(by the time I start) less than mine). You should read read about <a href="https://mailchimp.com/what-we-learned-from-the-recent-mandrill-outage/">MailChimp’s outage incident</a> partially triggered by an overflow of these + a vacuuming process not run].</p><p><strong><em>Lost updates.</em></strong><br>Consider a website visitor counter. Client A reads a value(1), Client B reads a value(1), Client A increments and stores the value(2), Client B increments and stores the value(2). The logic here intended for the final value to be a 3. A lost update though, means means we are still at a 2. You can work around this with atomic operations, for example a compare and set(<em>update where does this in some implementations</em>), makes it impossible here. Of course you’d have to make sure this is the case everywhere, otherwise you’ll still have this problem the moment any part of your application does a <em>read-update-write</em>. You can also use explicit locking, for example a <em>select for update</em>, which makes sure no one updates the value before you’re done with it.</p><p>A better approach though is for the database system itself to detect lost updates and abort transactions which saves us from having to unnecessarily lock data/ introduce unexpected locks.</p><p><em>Postgres, Oracle and SQL Server’s snapshot isolation levels do.</em></p><p><strong><em>Write skew.<br></em></strong>You can think of this as a more general lost update problem, the difference being the read/ constraint decision might be based on a different object than is being updated. For example, when claiming a username, preventing double spending, preventing double actions in a multiplayer online game, booking a meeting room. Sometimes, it might suffice to <em>materialize</em> the conflicts by creating the objects on which the conflicts will occur ahead of time, for example, room bookings, and locking them before acting on them, or adding better constraints on your data, for example a unique on room, booking, time.</p><p><em>Level of isolation that addresses these: Serializability.</em><br>Serializability guarantees that even though transactions may execute in parallel, the end result is the same as if they had executed one at a time, <em>serially</em>, without any concurrency. Thus, the database guarantees that if the transactions behave correctly when run individually, they continue to be correct when run concurrently. This can be achieved by literally executing them serially, two phase locking(if an object is affected in a transaction, no other transaction can act on it until that transaction is done) or optimistic concurrency control techniques like serializable snapshot isolation, which allows concurrent transactions but checks for conflicts before allowing a successful commit completion, which works in turn by keeping track of committed writes from other transactions that affect reads in the current transaction and aborting the transaction when it notices a write that it might have ignored due to snapshot isolation rules.</p><h3>Whatever can go wrong will go wrong</h3><blockquote>In my limited experience I’ve dealt with long-lived network partitions in a single data center (DC), PDU [power distribution unit] failures, switch failures, accidental power cycles of whole racks, whole-DC backbone failures, whole-DC power failures, and a hypoglycemic driver smashing his Ford pickup truck into a DC’s HVAC [heating, ventilation, and air conditioning] system. And I’m not even an ops guy.</blockquote><blockquote>— Coda Hale</blockquote><h4>Of Networks You Can’t Trust</h4><p>When you move from writing software that operates on a single computer to working with distributed systems, interesting and unpredictable things will happen often leading to partial lags/ failures in the system , and because unlike in single node systems, it is often not useful or practical to pull the whole thing down because of an isolated failure, we try our best to keep the system <em>working</em> as a whole. Being pessimistic will help you recover from these when they do happen. Reliable systems are often built from unreliable components, for example with TCP/ IP and error correcting codes in wireless networks.</p><p>The prevailing approach to building large scale systems is a <em>shared-nothing</em> one. Components in these systems therefore communicate over private networks or the internet, which introduces unpredictability and latency. For example, if a computer makes a failed request to another, it can sometimes be hard to tell at what point the request failed and whether it would be safe to retry it.</p><ul><li>Your request may have been lost (perhaps someone unplugged a network cable)</li><li>Your request may be waiting in a queue and will be delivered later</li><li>The remote node may have failed</li><li>The remote node may have temporarily stopped responding, but it will start responding again later(in which case it may have stopped responding before or after receiving your request)</li><li>The remote node may have processed your request, but the response has been lost on the network</li><li>The remote node may have processed your request, but the response has been delayed and will be delivered later (perhaps the network or your own machine is overloaded).</li></ul><p>And this is assuming your nodes are all working correctly(which is where replication and consensus help us to achieve correctness.)<br>In practice, several different things could cause network faults, unpredictable things like sharks biting an under sea cable for example. Network faults should be defined, tested, detected, handled and tolerated, the last two not being the same thing. Extreme approaches, like Netflix’s <a href="https://github.com/Netflix/chaosmonkey">Chaos Monkey</a> aim to randomly trigger such failures to ensure engineers are constantly thinking about them.<br>Detecting faults as quickly as possible is important as it helps you to quickly isolate the problem and prevent cascading failures. For example, a load balancer should know to stop sending requests to a failed node or a new leader should be elected as quickly as possible in a single-leader replication system in case the leader fails. Failures can be detected by refused TCP connections,monitoring scripts on dying node giving other nodes a heads up, routers responding with <em>destination unreachable</em> packets, etc.<br>Faults can be <em>crash-stop</em>, <em>crash-recovery</em>, or <em>byzantine</em>. You’ll need to expect these and define to what extent your system can recover from these failures.</p><p>Often though, delays make it hard to make a correct decision on whether or not a node is actually dead. Incorrect decisions can lead to creation of unnecessary load on a system by moving a node’s traffic to other nodes, for example. Unlike synchronous networks which can reserve a certain amount of bandwidth(circuit switching) for the communication between clients, TCP connections use as much bandwidth as necessary and switch traffic on packets instead which handle bursty traffic better.</p><h4>Time Is Not Your Friend</h4><p>Having an idea of <em>when</em> some action happened in your system is important. With distributed systems though, it’s hard to have a consistent global notion of time. Time-of-day clocks differ from monotonic clocks in that they can jump backward and forward in time, while monotonic clocks always move forward and are generally safe for measuring elapsed time.</p><p>Synchronizing clocks can still be aimed for with;</p><ul><li>Approaches like the <em>Network Time Protocal </em>try to have computers synchronize their clocks by depending on central servers which in turn depend on more accurate sources. NTP can then set time of day clocks or slow or speed up the monotonic clock in or to have it keep pace with the server clock.</li><li>Approaches like Google’s <em>TrueTime</em> API in their Spanner database explicitly make the time uncertainty clear by reporting an <em>earliest</em> and <em>latest</em> time which then lets the database make ordering decisions based on if the entire time range is less than or greater than the other other and sometimes waiting artificially to ensure the two time periods do not overlap.</li></ul><p>Even with these approaches, you still have issues like;</p><ul><li>Computers drifting from the main time servers’ time and there is a bounded accuracy you can hit with this approach because of network delays and the clock can differ too much sometimes that a reset would be necessary.<br>[Servers, plural, because clients can query multiple servers to come to a consensus]</li><li>Accidental fire-walling from the time servers</li><li>Incorrect configs</li><li>Leap seconds(one way of solving this is by <em>smearing, </em>which is gradually compensating for the second instead of having a phantom extra second)</li><li>Virtualization on a single core causing surprising time jumps from VM pauses</li><li>Process pauses, for example due to garbage collection, or computers going to sleep on user request or context switches or any other action causing preempting of the thread, can cause decisions made based on current time to be incorrect when a pause happens immediately after</li><li>Users may intentionally set an incorrect time on their devices(for example, evading game play rules)</li><li>Failures can be very bad especially because they are hard to detect</li></ul><p>In regards to timing assumptions, you have to decide on whether your system will be synchronous, partially synchronous or asynchronous.</p><h4>It’s A Democracy</h4><p>Because we acknowledge all the things that can wrong we there have to fall back on relying on redundancy. The truth is defined by the majority. For example, for a leader to be declared dead, the majority of the nodes must agree on this and have a strategy for preventing dissent to this decision, for example the dead node refusing to stop acting as the master if it was previously one, by for example, introducing fencing tokens to ensure locks obtained by clients are still valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*_x0MD9g6GvDB_gK5gvZzFQ.png" /><figcaption>Making access to storage safe by allowing writes only in the order of increasing fencing tokens.</figcaption></figure><p>Depending on the majority only works when all nodes are acting in good faith though, meaning it can’t quite protect you from Byzantine faults, which is where a node inadvertently- due to some part of the system failing or intentionally- an attack by an intruder, acts in error.<br>Weak forms of lying can be solved by adding infrastructure/application level safety guarantees- sanitizing input, correcting corrupt packets, etc.</p><p>When designing algorithms to handle these problems, they must have certain properties in order to achieve the goals we set out to achieve. Proving that an algorithm does have these properties may not mean it will in practice, but it is a start.</p><ul><li>Correctness- which may in turn be defined by properties like enforcing uniqueness, monotonic sequences and availability.</li><li>Safety(nothing bad happens) and liveness(how long will the good thing take to <em>e</em>ventually <em>ha</em>ppen)</li></ul><h3>Of Guarantees In A Distributed World</h3><p>We’ve seen a few useful guarantees your database can give you. What we’ve not done though is moved them to a distributed(replicated in this case) world.</p><p>Like we’ve seen, lots of things can go wrong with distributed systems. Often, failures happen in some component and not necessarily across the entire system. The question is what we decide to do when this happens. The most straightforward thing would be to let the entire service fail- which is correct, but often now helpful. We try to compensate for these failures and attempt to recover or correct issues we encounter.<br>Often, we try to find some general purpose, useful guarantees, implement them, and then let applications use them[just we did with transactions]. This allows applications built on top of these abstractions to pretend that these problems do not infact exist as long as these primitives are understood and used correctly.</p><p>Most databases provide at least <strong>eventual consistency</strong>. Which means all replicas will <em>eventually </em>converge to the right value. No guarantee on what <em>eventually</em> means. This often means application developers have to think about these problems all the time, creating all sorts of issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*iGBH1Q0nm6lV-og9UPGHSQ.png" /><figcaption>Not Linearizable</figcaption></figure><p>This means if you asked different replicas a question at the <em>same time</em>, you might get different answers. An easier way to reason about the system would be if when one client completes a write, all clients reading from the database[because clients don’t care that it’s replicated] could see this write. This guarantee is called linearizability, whose goal is to make a system appear as if there is only a single copy of the data, a.k.a- if something happened, it happened.</p><p>To implement linearizability, we start by first guaranteeing that reads that happen after completed writes see the new value. We then have to deal with overlapping operations. We need to guarantee that once a client reads a new value, all clients that read it next must not read an older value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*If8HG_DHAwldAqLOrBdw9Q.png" /><figcaption>We effectively have a thread through the transactions. Any action that cannot fit into this thread would not be successful.</figcaption></figure><p>Single leader replication systems and consensus algorithms are linearizable but multi leader and leaderless replication aren’t.<br>Something to remember is to not mix up serializability(guaranteeing that the effect of transactions is as though they were run one after the other) and linearizability whose goal is to make it to clients like there exists a single copy of the database. Databases may provide both linearizability and serializablity- known as strict serializability, which is quite a strong guarantee.</p><p>Having strict read/ write quorums does not make a system linearizable, because of the network latency with replication, which means that clients can still read from multiple replicas with stale values and hit the quorum[read repair can help with this, but at a performance hit].<br>In general, it looks like few systems are indeed linearizable and making them so comes at a performance hit proportional to the uncertainty of delays in the network.</p><p>339</p><p><em>inadvertently</em></p><p>MapReduce -&gt; Hadoop -&gt; Hive/Airflow?</p><p>DAGS -&gt; Spark -&gt; Hive/Airflow?</p><p>key takeaways</p><ul><li>software is just software</li><li>dbmss implement a wide varitey of mature features. you should pay more attention</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8275e325826" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Of Modular Alembic Migrations]]></title>
            <link>https://medium.com/@karuhanga/of-modular-alembic-migrations-e94aee9113cd?source=rss-28289fc41654------2</link>
            <guid isPermaLink="false">https://medium.com/p/e94aee9113cd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[alembic]]></category>
            <dc:creator><![CDATA[Karuhanga Lincoln]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 07:40:46 GMT</pubDate>
            <atom:updated>2020-07-06T07:45:32.745Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>This piece was born more out of surprise than anything else. Given how much we take modularity for granted, I assumed it would be a first class concept in something as widely popular as <a href="https://alembic.sqlalchemy.org/en/latest/index.html">Alembic</a>(which for the record is quite stellar and I have enjoyed working with it).</p><p>The goal here is to share an approach to this problem that’s worked well for my team and hopefully save you a few nights along the way.</p><h3>Goal</h3><p>Track a project’s applications’ migrations separately, both conceptually and in alembic.</p><h3>Approach</h3><p>If you’ve worked with a recent version of Django, you’ll agree handling migrations there are pretty seamless. In particular, the approach with applications is intuitive. The goal was to replicate something of the sort here. The assumption is that each app has at least one separate schema. I have not yet tried using a schema cross app, but there’s no reason it should fail. Our team uses a dev script at the top of a project directory with wrappers to common commands. At the end of this we’d like to have at least three commands;</p><ul><li>./dev makemigrations: generate migrations for recent model changes(we’ll default to auto generated migrations)</li><li>./dev migrate &lt;app_name&gt;: apply generated migrations to the database</li><li>./dev downgrade &lt;app_name&gt;: revert the last applied migration</li><li>Bonus- ./dev create &lt;app_name&gt;: sets up a new application</li></ul><h3>Show me the code</h3><p><em>If you have not yet given the docs a run through, now would be a good time. Otherwise, going forward, I assume you have run the </em><em>init command and have an environment similar to </em><a href="https://alembic.sqlalchemy.org/en/latest/tutorial.html#the-migration-environment"><em>this</em></a><em>.</em></p><h4>Set Up Common Migration Functionality</h4><ul><li>Add an [alembic] section, which will hold the config to be used when now a --name is not specified when running alembic commands. We’ll use this for things like checking collective head statuses. For now, just add this to that section;</li></ul><pre>[alembic]<br># universal config<br>script_location = alembic # dir where your common `env.py` file lives</pre><ul><li>Modify the env.py file generated by alembic to;</li></ul><pre>from logging.config import fileConfig<br>from typing import List<br><br>from sqlalchemy import engine_from_config, MetaData<br>from sqlalchemy import pool<br>from alembic import context<br><br>import settings<br><br># this is the Alembic Config object, which provides<br># access to the values within the .ini file in use.<br>config = context.config<br><br># Interpret the config file for Python logging.<br># This line sets up loggers<br>fileConfig(config.config_file_name)<br><br># other values from the config, defined by the needs of env.py,<br># can be acquired:<br># my_important_option = config.get_main_option(&quot;my_important_option&quot;)<br># ... etc.<br><br><br>def _include_object(target_schema):<br>    def include_object(obj, name, object_type, reflected, compare_to):<br>        if object_type == &quot;table&quot;:<br>            return obj.schema in target_schema<br>        else:<br>            return True<br><br>    return include_object<br><br><br>def _run_migrations_offline(target_metadata, schema):<br>    &quot;&quot;&quot;Run migrations in &#39;offline&#39; mode.<br><br>    This configures the context with just a URL<br>    and not an Engine, though an Engine is acceptable<br>    here as well.  By skipping the Engine creation<br>    we don&#39;t even need a DBAPI to be available.<br><br>    Calls to context.execute() here emit the given string to the<br>    script output.<br><br>    &quot;&quot;&quot;<br>    url = settings.CONNECTION_STRING<br>    context.configure(<br>        url=url,<br>        target_metadata=target_metadata,<br>        literal_binds=True,<br>        dialect_opts={&quot;paramstyle&quot;: &quot;named&quot;},<br>        <strong>include_schemas=True,  #1</strong><br>        <strong>include_object=_include_object(schema),  #1</strong><br>        compare_type=True,<br>    )<br><br>    with context.begin_transaction():<br>        context.run_migrations()<br><br><br>def _run_migrations_online(target_metadata, schema):<br>    &quot;&quot;&quot;Run migrations in &#39;online&#39; mode.<br><br>    In this scenario we need to create an Engine<br>    and associate a connection with the context.<br><br>    &quot;&quot;&quot;<br>    connectable = engine_from_config(<br>        config.get_section(config.config_ini_section),<br>        prefix=&quot;sqlalchemy.&quot;,<br>        poolclass=pool.NullPool,<br>        url=settings.CONNECTION_STRING,<br>    )<br><br>    with connectable.connect() as connection:<br>        context.configure(<br>            connection=connection,<br>            target_metadata=target_metadata,<br>            <strong>include_schemas=True,  #2</strong><br>            <strong>include_object=_include_object(schema),  #2</strong><br>            compare_type=True,<br>        )<br><br>        with context.begin_transaction():<br>            context.run_migrations()</pre><pre><br><strong>#3</strong><br><strong>def run_migrations(metadata: MetaData, schema: List[str]):<br>    if context.is_offline_mode():<br>        _run_migrations_offline(metadata, schema)<br>    else:<br>        _run_migrations_online(metadata, schema)</strong></pre><p><strong><em>Key changes</em></strong></p><p><strong><em>1, 2.</em></strong><em><br></em>The default generated file does not have the include_schemas flag turned on. I faced difficulty with getting alembic to find model changes across schemas with this flag off. However, turning that on also led to migrations in other schemas being wrongly attributed to whatever schema I was trying to migrate at the time. Addressing this is where the include_object argument comes in. It takes a method which when called should return True or Falsebased on whether or not it should be included in the generated migration file.</p><p><strong><em>3.</em></strong><br>Running the migrations is no longer done when the file is loaded/ executed, rather when this method is called. The schema allows us to do the filtering mentioned earlier**.</p><h4>Creating An App</h4><p><em>Hopefully, by the end of this, we’ll have a command(</em><em>./dev create &lt;app_name&gt;) to automatically do this boiler plate work, but until then, add these steps to your README because you’ll need to do them every time you add a new application.</em></p><ul><li><strong>Add a migrations directory</strong> to your application(convention here is &lt;app_name&gt;/migrations, but feel free to follow your project’s convention, e.g migrations/&lt;app_name&gt;).</li><li><strong>Copy the</strong><strong>script.py.mako file to this directory.***</strong></li><li><strong>Create an </strong><strong>env.py file in this directory</strong> and add;</li></ul><pre>from alembic.env import run_migrations  # or wherever your common `env.py` file is<br>from &lt;app_name&gt;.models import Base<br><br>metadata = Base.metadata<br>schema = [&quot;some_schema&quot;, &quot;some_other_schema&quot;]<br><br>run_migrations(metadata, schema)</pre><p>The format of this file will be more or less the same for all applications, with the relevant schema and Base model class swapped in.</p><ul><li><strong>Add your app’s section</strong> with the appropriate attributes to alembic.ini. This will suffice for now;</li></ul><pre>[your_app_name]<br># &lt;app_name&gt; specific settings<br>script_location = &lt;app_name&gt;/migrations</pre><ul><li><strong>Add your app’s migration directory to </strong><strong>alembic.ini/version_locations.</strong> This will allow alembic keep track of all the places your migrations live even when you are running alembic using a different section of the alembic.ini file with different version locations and have different version bases.</li><li><strong>Create your first migration;</strong></li></ul><pre>alembic \<br>    --name=&lt;app_name&gt; \<br>    revision -m &quot;&lt;message e.g Initial: Setup Models&gt;&quot; \<br>    --head=base \<br>    --branch-label=&lt;app_name&gt; \<br>    --version-path=&lt;path to your app&#39;s migration files e.g &lt;app_name&gt;/migrations/versions&gt; \<br>    [ --autogenerate]</pre><p>Let’s break this down.</p><ul><li>--name allows us to choose the section in the config file to use****.</li><li>--head=base says to start this migrations tree at the root, meaning it’ll have no previous dependencies. This makes sense for our application approach.</li><li>--branch-label will be the name of this migration branch. Read about <a href="https://alembic.sqlalchemy.org/en/latest/branches.html">branches</a> in the docs to dig into this.</li><li>--version-path is pretty self explanatory. You probably want to auto discover model changes, so include the --autogenerate flag.</li><li><strong>Migrate.<br></strong>Run this app’s first migration.alembic --name=&lt;app_name&gt; upgrade &lt;app_name&gt;@head.</li></ul><h4>Add The Convenience Commands To Your dev Script</h4><p><em>After running the previous steps and after setting these up, you’ll subsequently just be running </em><em>./dev makemigrations when your models have new changes and </em><em>./dev migrate to apply them.</em></p><ul><li>Add a ./dev makemigrations -m=&quot;Some message&quot; &lt;app_name&gt; command that you’ll run for migrations going forward*. That command runs;</li></ul><pre>alembic \<br>    --name=&lt;app_name&gt; \<br>    revision \<br>    --message=&quot;Some message(your migrate command should probably take this in as an option)&quot; \<br>    --head=&lt;app_name&gt;<a href="http://twitter.com/head">@head</a><br>    --autogenerate</pre><p><em>*For the first migration in an app, you’ll run the command in </em><strong><em>Create your first migration </em></strong><em>above and for subsequent ones, you’ll run this one</em>.</p><ul><li>Add a ./dev migrate &lt;app_name&gt; command that runs alembic --name=&lt;app_name&gt; upgrade &lt;app_name&gt;@head like above.</li><li>Add a .dev downgrade &lt;app_name&gt; command that runs alembic --name&lt;app_name&gt; downgrade &lt;app_name&gt;@head-1.</li></ul><h4>Footnotes</h4><ul><li>**: If you have a single schema per app, you could even exclude this and pick the schema from the metadata.</li><li>***: If you figure out a way of having alembicuse the earlier generated envfile, while at the same time pointing to a script location that’s not that directory, let me know :)</li><li>****: We can do interesting things with this one. For example, I tried auto discovering the schema and modules based on this but it didn’t quite end well. That’s something that <em>might</em> still be possible and <em>might</em> eliminate the need for the app specific env files.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e94aee9113cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Awesome]]></title>
            <link>https://medium.com/@karuhanga/the-awesome-c881d6444b0c?source=rss-28289fc41654------2</link>
            <guid isPermaLink="false">https://medium.com/p/c881d6444b0c</guid>
            <category><![CDATA[diversity]]></category>
            <category><![CDATA[diversity-in-tech]]></category>
            <category><![CDATA[team]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Karuhanga Lincoln]]></dc:creator>
            <pubDate>Wed, 24 Oct 2018 12:49:10 GMT</pubDate>
            <atom:updated>2018-10-24T13:49:34.539Z</atom:updated>
            <content:encoded><![CDATA[<h4>If they shot a movie about your life, what genre would it be</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yS4MHEHfSCfWbXN0yTku6w.jpeg" /></figure><p>It’s not everyday that you get thrown in with a group of total strangers and told <em>‘Hey, you gotta make this work’</em>. It does help though if the people are a friendly, challenging bunch. You quickly get endeared to them and soon enough, you’re in love. These short stories don’t do any of them justice, but, hey, I tried.</p><h4>Mystery and Action</h4><p>Probably the most all round person I know, well save for the being single part, Ben is very single. Ben values friendship. Ben values fun. Ben is big on life. Ben is good. And when I say <em>good </em>I mean both technically and as a human. The technical comes from valuing hard work. Setting a goal and putting the work in to reach, nay, beat that goal. Anyone one of these qualities is amazing on its own and put together, they make a person that is simply a joy to work with. As to Ben’s name being <em>mystery and action</em>, I’ll just say we see life through different lens. His happens to tell him he is living life with a touch of mystery so we won’t dispute that.</p><h4>Docudrama</h4><p>You can tell a lot about a person from the way they introduce themselves. Not exactly what or who they are, but exactly who they think they are. This obviously drives intent. And human beings generally judge themselves on intent(- never mind the fact that we judge others on outcome). Nathan introduces himself as an Agricultural Scientist. He sees this as a plus and passionately pushes on with it, and you can tell from the way he does this that he is proud of what he does and seeks to see how can broaden his perspective, while using the knowledge he has to make everyone else better. He seeks to get knowledge on this whole new perspective to apply it and see it benefit everyone in the end. A docudrama is dramatized television film based on real events. While not entirely accurate, I felt this is the perfect description for a person that takes reality and pushes the boundaries of what we believe with what he believes.</p><h4>Thriller and action</h4><p>The thing that’s probably at the top of my <em>why I love Andela list</em>, (yes, there’s a list) is the diversity. I love that diversity. There’s a whole lot of possibilities. Things to talk about, ideas to think up. Crazy ways to break things. Everyone on this team comes from a different school of life and everyone exemplifies this diversity and I do know it is quite cliché to bring up gender in the same sentence as diversity, but tech has this problem and there’s very few people doing anything about it. Joan brings a blend of knowledge, a sense of adventure and curiosity to the team and my is it awesome. Joan is also a reader and that alone says a lot. There’s a certain depth that come with acknowledging that there’s a whole range of perspectives to which you can be exposed and I think this team has seen first hand the fruits of that. She is also probably the only one that earns their name <em>thriller and action</em>.</p><h4>Reality/ Biography(if that were a genre)</h4><p>It’s about being humble. Not flaunting your knowledge all the place. Keeping calm. He values being in love with himself. <em>Know thyself</em>. Keeping away from the chaos that life can be. He is very objective. None of the crazy catch words people are endeared to, none of the shallow responses people are tuned to throwing you. He is quick to point out though, that he is <strong>not </strong>an introvert- he hates stereotypes. He is just him. Just a guy making his own way in the world, nothing to see here. I think this keeps the team on the ground- grounded in reality so to say. Micheal. Reality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c881d6444b0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You’re an introvert. We get it.]]></title>
            <link>https://medium.com/@karuhanga/youre-an-introvert-we-get-it-b315c2f3967?source=rss-28289fc41654------2</link>
            <guid isPermaLink="false">https://medium.com/p/b315c2f3967</guid>
            <category><![CDATA[andela]]></category>
            <category><![CDATA[introvert]]></category>
            <dc:creator><![CDATA[Karuhanga Lincoln]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 13:10:13 GMT</pubDate>
            <atom:updated>2018-10-22T20:08:55.584Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Dear Lincoln,</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*UeTM_mnUMZGIo5YGU-Im9A.jpeg" /></figure><blockquote>“No. I’m not. I don’t like using it. I’m an introvert.”</blockquote><p>If my nose grew longer every time I heard that statement, I’d be Pinocchio. There seems to be a growing <em>thing </em>where people suddenly declare they are introverts. And they have always been. Try to convince them otherwise and “<em>no, you don’t get it. You never will.”</em> They are made from different stuff. The rest of us <em>friendly </em>people have some kind of pathetic need to be loved.</p><p>Then there’s the;</p><blockquote>“<em>Oh. So you’re an introvert?” “No. I didn’t say that. I said I’m comfortable being by myself</em>”.</blockquote><p>The rush to generalize. Throw people into boxes without hearing them out.</p><p>I’d stay away from hypothesizing on what suddenly causes this shift. I wouldn’t even call it sudden. I think it’s a kind of indoctrination from all these stories we hear. Like see this billionaire that built this thing alone in his garage. See how rich he is now, the lone wolf. The media makes it all look quite <em>sexy</em>. The behind the scenes is never a thing people care about. The shine is what matters. I know so many people doing big things- trying to do big things. I find it sad that when they do need to talk to someone, they can’t find said person. It doesn’t help that everyone else is, well, <em>shallow</em>, which is not entirely untrue, but sometimes simply is not the point. I’ve had extremely deep conversations with people of contrasting depth and they are some of the ones I hold dear. You don’t live in a bubble… or at least, you shouldn’t. I’ve learned that people wear this self anointed status as some kind of badge of honor. It shouldn’t be. I’ve learned that people try to be someone else yet they can be insanely interesting versions of themselves. You surely cannot expect to be the one guy working on all the interesting stuff. Other people have dreams to. You need to start focusing on how you can help them achieve their dreams as well. Think, how can I help you be awesome today? You should take the back burner.</p><blockquote>Bottom line: People are amazing. It really is not about you.</blockquote><h4>Really, I’m too lazy to try</h4><p>I’ve learned that <em>“I’m an introvert.” </em>is sometimes a fallback for not wanting to take the effort. No one cares how you feel. People watch what you do. You don’t have to be the most interesting person, though it certainly doesn’t hurt to be a touch funny, a touch outgoing. People need to see you make the effort. People appreciate it. A friend of mine recently made a comment about being over <em>hi, bye </em>relationships- you know those people you’ll literally only ever say hi and goodnight to. I’ve heard this big talk thing a lot. There’s even a TED talk and whole movement about it. The entitlement of wanting some kind of automatic deep connection baffles me. The fact is small talk will take you places. We can’t all have <em>deep</em> conversations with everyone we meet. It’s just, well, then there wouldn’t be a deep, would there? You need to talk to people, however shallow the conversation will be.</p><blockquote>“Small talk will take you places.”- <em>Andrew Omoding</em></blockquote><p>You’ll need a leg up. There are so many coincidences in life. You’ll coincidentally meet at an interview. You’ll update your status needing help with that application. They’ll know somebody. Create some more of these coincidences. Create your own luck. They’ll challenge you. Like oh you write… do you? Because they actually do and you’ll eventually have to live up to this claim you know. It’s amazing how much one person can change the course of your life in this respect. Accountability is the word for it. Then there’s <em>fate</em>. I don’t think fate is a thing. So much goes on. So many decisions- some split second that could go one way or the other. I’ve learned that knowing more people and learning from more experiences means you’re more likely to make better ones. I can’t emphasize enough how many opportunities I’ve missed out on in the past because of not knowing this.</p><h4>People don’t get me</h4><p>Having a low EQ is not being an introvert. Don’t be selfish. Don’t be proud. What is it about you that you think is so bad(or so good) you can’t have other people in your life? You aren’t special. There’s 7 billion other people and, again, you aren’t really unique. Not in that way at least. Get over yourself. You’re not all hard and <em>macho</em>. Don’t get me wrong though, I think everyone’s special and I don’t think the world will benefit from a sudden rush of <em>wannabe</em> extroverts, but I don’t think we’re doing any better with all the <em>wannabe</em> introverts. There will be dark times. You’ll need to talk to someone. Only then will you really know you weren’t really an introvert and that people do in fact ‘<em>get you’</em>.</p><p>This school of thought normally goes along with statements like; People are time wasting. We have dreams to achieve. Social media wastes quite a load of time. There’s a lot friendship fatigue. All sometimes true, but all usually used as an excuse for deeper belief- or a lack of it. It’s like being a loner is sometimes… you know… <em>cool</em>. I’ve learned though that people don’t care how much know until they know how much you care. We need to interact. We need to share ideas. Someone has to break that ice. Reach out. You are going to die. We all are. Eventually. You are following a path someone else has probably followed- don’t make the same mistakes. Also, some things are also all the more special if you share that experience with someone that’s been there. Don’t miss that.</p><blockquote>I write all this from a place of self discovery. A journey I’ve been on for about a year. I feel this way sometimes. I’ve recently learned I don’t need to, or I at the very least don’t need to shout about it.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b315c2f3967" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Siri still won't say Buganda right!]]></title>
            <link>https://medium.com/@karuhanga/why-siri-still-wont-say-buganda-right-1f4b03e03ec8?source=rss-28289fc41654------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f4b03e03ec8</guid>
            <category><![CDATA[net-neutrality]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[uganda]]></category>
            <dc:creator><![CDATA[Karuhanga Lincoln]]></dc:creator>
            <pubDate>Sun, 10 Jun 2018 16:14:43 GMT</pubDate>
            <atom:updated>2018-06-11T13:21:50.310Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Siri still won’t say ‘Buganda<em>’</em> right!</h3><p>If you’re like me, you’ve probably run out of silly things to say to your virtual assistant, just to tease that equally silly answer out of it. In all honesty, Africans have never really been early adopters and virtual assistants are something still out of this world for the bulk of us. If you are looking for a symbol of just how far the tech world has come though, then look no farther.<br>Something that is consistently apparent though is; even while the assistants clearly get ever so smart, they seem quite impressively culturally oblivious, especially in the African context. Why? Obviously, the short answer to this would be;</p><blockquote>Short answer; Siri doesn’t have enough Ugandan friends</blockquote><p>But where’s the fun in that? The long answer is a bit more of a rollercoaster;</p><blockquote>Long answer; Here we go;</blockquote><h3>Preamble. Life of Lame-Tea-Hen</h3><p>Say I’m a telco in Uganda, we’ll call me LTH. I’ve has been around for quite a while, all through the time Nokias and <em>pakalast</em> were still a thing, even before this mobile money cash cow came along. I’ve seen competitors come and go, I’ve reaped from government exclusivity agreements. Basically, I’ve seen it all.<br>Then some guy invents the smart phone, some other guys follow this up and build this <em>Android</em> thing, wireless network standards improve just enough to allow near real time communication and the last straw, VoIP and instant messaging services popup, along with this social media wave. To keep profits up, I set the high data prices of course, seeing as my voice and SMS profits are declining. But not to worry, more people are getting on board the smart phone wave, so I’ll just sell more data expensively. Never mind <a href="https://www.investopedia.com/terms/e/economiesofscale.asp">economies of scale</a> (the marginal cost of maintenance for a new customer is virtually negligible); there’s little regulation- not that majority of the regulators fully understand how these things work.<br>I know you’re thinking ‘<em>nah, this is a free market capitalist economy- someone will blow you out the water’</em>. Right? Wrong.<br>Well for one, remember that exclusivity agreement? I now have a vast amount of infrastructure. And that’s a huge deal here. Any competitor will probably want to lease my mast in the first place. Then they’d have to get into interconnection arrangements and then somehow undercut my price… you get the drill. It’s messy. Humans fear messy. I’m okay.</p><p>However, let’s assume for a moment that someone does achieve the bare minimum to start competing; I lower my product prices by small chunks where necessary, just enough to always stay competitive. Switching mobile service providers isn’t an easy ask for the average consumer. They’ll need to see a huge improvement- <a href="https://www.forbes.com/sites/gregsatell/2014/10/03/peter-thiels-4-rules-for-creating-a-great-business/#3673461454df">at least 10X</a> according to Peter Thiel, this compounded by the fact that Uganda has no such thing as <a href="https://en.wikipedia.org/wiki/Mobile_number_portability">Mobile Number Portability</a>- your contact following you when you switch telecom providers. And again, nearly all your friends use my network, which makes getting in touch with them slightly more costly if you switched; unless you all moved together (hint: you probably won’t).</p><h4>The social bundle (r)evolution</h4><p>Eventually, the steam runs out from anyone that dares to compete and things get back to normal. Except, not really; things never get back to ‘normal’, the price inevitably comes down, just a little- effectively. So if enough companies make me play this game, they’ll be eating into my profit margins. Granted, my expenditure on the core technology is probably going down, but I still need to show the increasingly demanding investors healthy results. Fortunately, in the meantime, I’m pretty lucky and this mobile money thing comes along. I play this right, do a country wide roll out and voila; a whole new revenue stream.</p><p>My problem persists though. Basically, the mobile data part of my service is not justifying the investment. Profits aren’t what they used to be with voice and SMS. So what do I do? Someone pops out this genius pricing strategy. Fancy sounding name and all. <a href="https://en.wikipedia.org/wiki/Pricing_strategies#Premium_decoy_pricing">Premium decoy pricing</a>. ‘<em>This could work’</em>, I think to myself. Except, you can’t really offer two different versions of the internet, can you? So I look around, and take a hint from this Facebook Zero thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYKIWnwlDji4ah5NVrkJgA.jpeg" /><figcaption>A bubble? (Credits: <a href="http://www.muchimmo.com/social-media/">Muchimmo</a>)</figcaption></figure><blockquote>‘It seemed that in their minds, the Internet did not exist; only Facebook.’- <a href="https://qz.com/333313/milliions-of-facebook-users-have-no-idea-theyre-using-the-internet/">Helani Galpaya</a></blockquote><p>‘<em>Hmmm, folks actually think Facebook is the entire internet’</em>. There is certainly something here. So I <strong>swift</strong>ly introduce this new too deficient to be true bundle. <strong>The WTF pack</strong>-<strong> </strong>which true to its acronym, stands for WhatsApp, Twitter and Facebook. What’s in it you say? Well, I’ll offer you 0.0000000006% of the internet at about half the prevailing cost. Yes, nine zeros. Again, I hear you cry; ‘<em>no sane person would go in for that’</em>. But that’s exactly what they did. Data sales went way up, and I can justify the mobile data investment- in them meantime.</p><p>I’ll put this in a single statement. I made sure to ask on <a href="https://www.quora.com/Why-would-a-telecom-company-restrict-access-to-the-Internet-to-only-social-media-if-they-arent-being-paid-to-do-it-Are-there-some-kinds-of-optimizations-that-can-make-it-cheaper-to-provide-Internet-access-to-only-a">Quora</a>, prior to this.</p><blockquote>‘There is no justifiable reason, technically, that would make access to a selection of platforms on the web cheaper than access to the entire breadth of the internet.’</blockquote><p>I believe it is very important for us to make this distinction though; numerous telcos show some kind of preferential treatment to popular social media products- as <a href="https://public.tableau.com/profile/zeroratingcts#!/vizhome/zeroratinginfo/Painel1">this map</a> shows. The majority of the models are centered around either zero rating the products (kajambo Facebook Zero) or bundling the zero rating offer as part of a purchased bundle. Business. Except, the Ugandan model is specifically built around the hope that the users <strong>will be</strong> naive. I am not graying things out here, net neutrality is a black and white issue. There is no <em>middle ground. </em>Both models are just as wrong, but I find the one we are subjected to honestly insulting, and I refuse to believe that the telcos don’t realize they are doing this.</p><p>Notice I have made two arguments here; the first is economic. Telcos don’t lose anything by simply lowering all (artificially high) data bundle prices to the social media price point they have created. The long term implications of this is a no-brainer really- local products will at the very least have a shot at adoption and there will inevitably be more data consumption directly, indirectly and not related to the former consequence. The importance of the former is often understated though, because of the terrible startup culture. At their best though, startups can produce life changing products that become an important part of society.<br>The second is intellectual. We are killing the next generation by keeping them from the troves of knowledge the internet is so full of.</p><p>As a side note; one of the last people I spoke to as I was getting ideas for this article nearly made me give up this argument. He says, ‘<em>telcos need a way to regulate the huge surge of traffic generated by users of primarily social media products; hence throttling the speed of access to the platforms generating this traffic, by placing them into their own class’- </em>hence the WTF packs. While this is a tempting argument, it bundles two fundamentally different issues together- the need to keep traffic levels to what the infrastructure can handle, and how the company chooses to do it. It seems insane that the how would be cutting out platforms that don’t generate all this traffic in the first place and restricting people to those that actually do.</p><h3>Soon enough, Safeboda gets zero rated</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aCjHfWbEg6kiv9wI" /><figcaption>Photo by <a href="https://unsplash.com/@bernardhermant?utm_source=medium&amp;utm_medium=referral">Bernard Hermant</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>On 4th May 2018, Safeboda and MTN made an <a href="http://www.dignited.com/30619/safeboda-is-not-zero-rated-on-mtn-uganda-hail-a-boda-without-mbs/">announcement</a> that I assume both think is in each of their best interests. Safeboda would get zero rated, that is data use on the Safeboda platform will not count towards your purchased data bundle. A <em>win </em>for MTN- a nice marketing gimmick to go along with their <em>Nofear </em>campaign. A win for Safeboda because, well, pillions don’t need to have an active data bundle to hail a ride, and neither do the riders, while accepting one. Not that they have the data bundle anyway since they are on the social bundles. Now I have been a consistent advocate for and customer of Safeboda (<em>pats self on back</em>). I believe their people centered model is proof that truly stable businesses can emerge from startups in emerging economies. This decision though, is directly detrimental to the same Ugandan startup community that has faithfully had their backs. Great, you have gotten the coveted zero rating, and are probably getting more rides moving along (I seriously doubt this- but that’s a whole other discussion). You now have a competitive advantage. Hooray.</p><p>But… what about other startups that aren’t your direct competitors? What precedence does this set for them? By definition startups are lean entities, many of which might not have access to the amount of funding Safeboda does and will therefore not be able to grease telcos hands. And yes, you might ask what way out you have, given the current status of the ISPs in Uganda; but what does that say about a startup, that has grown to have such a level of influence, rarely achieved by Ugandan startups, but declines to use that influence to advocate for change, even in the slightest. It is business. I know. But that hardly makes it right.<br>If you’re thinking we could just zero-rate all Ugandan startups, I wonder were the end in that would be and whether we could trust telcos to stay neutral when the said startup is a competitor in some way.</p><h3>And now the crazy. Let’s tax social media</h3><p>Sure, why not?<br>Government’s primary role in a space where no government entity exists (UTL is long dead), is to regulate the private sector and ensure the markets work fairly, giving no one an unfair advantage that would be detrimental to the consumer, whether or not the consumer himself/herself acknowledges it. The government of Uganda on the other hand seems to have adopted a position that views citizens as cash cows, and instead jumps on to the telcos bandwagon and rolls out this <em>genius </em>(I assume someone upstairs thought so) idea to tax social media use.</p><p>I acknowledge that governments need revenue to function. Fair enough. If this is the case though, then why not impose taxes on the companies themselves? These companies are largely <a href="https://www.iafrikan.com/2017/12/05/how-tech-giants-are-making-the-taxman-in-africa-dance-azonto/">given a free pass</a> — mostly because government has no idea how to deal with them.<br>I suspect I’ll get called out on directly contradicting myself in now going against attempts to regulate the use of social media (the reason government gave for the move) after previously condemning it’s preferential treatment, but make this distinction; Net neutrality, for better or worse gives every single entity uniform access to the opportunities the internet affords.</p><p>Again, the better product and strategy should always be the determining factor as to who wins. What is even more interesting is that none of our representatives in parliament sees this as an issue in the slightest. Their well worn argument was that this constituted double taxation. I am not an economist, and I will not give a verdict on that. The bottom line is; the Internet was founded on certain principles. Being an Internet Service Provider should- if not by principle, then by law, necessitate providing access to the Internet fairly, and in its entirety.</p><h4>So here’s why Siri might never get it right;</h4><blockquote>Siri thrives on experience. The more interactions she gets, the smarter she gets. Since she’s not getting any attention from Ugandans (that is the Ugandan market is not strong enough to justify special consideration), she’ll inevitably be terrible at these interactions. But it’s not all about Siri. It’s about just about any product out there. The internet is a platform that bears promise. Promise that the best ideas will filter through, promise that modest companies can compete with mammoth ones favorably; with the right strategy, and promise that only the consumer’s choice will drive adoption. These products simply stand no chance with the current state of the internet in the country.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f4b03e03ec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>