<?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 Ayrton Werck on Medium]]></title>
        <description><![CDATA[Stories by Ayrton Werck on Medium]]></description>
        <link>https://medium.com/@werckayrton?source=rss-af5767742e37------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FtbR1WeBAhmWkCQv.</url>
            <title>Stories by Ayrton Werck on Medium</title>
            <link>https://medium.com/@werckayrton?source=rss-af5767742e37------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 23:42:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@werckayrton/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[Designing data intensive application — Chapter 4 — Part 2]]></title>
            <link>https://medium.com/@werckayrton/designing-data-intensive-application-chapter-4-part-2-ab8ebbaf04f4?source=rss-af5767742e37------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab8ebbaf04f4</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Ayrton Werck]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 08:49:39 GMT</pubDate>
            <atom:updated>2022-12-30T10:43:27.027Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modes of data flow</h3><p>We saw that to send data between process that doesn’t share the same memory we have to encode that data and we discussed various ways of encoding.</p><p>There are three ways the data flow between process.</p><h3>Through Databases</h3><p>Process that writes to the database encodes the data and process that reads from the database decodes it.</p><p>Multiple versions of an application may access the database at the same time. New code must be able to read old code as well as the old code must not break when a new code writes new data.</p><p>When old code update records, you have to make sure it left the new field intact. It is generally supported by the encoding format we talked about previously but sometimes it has to be handled at the application level.</p><p>Rewriting (<em>migrating</em>) is expensive, most relational databases allow simple schema changes, such as adding a new column with a null default value without rewriting existing data. When an old row is read, the database fills in null for any columns that are missing.</p><h3>Through Services: RPC and REST</h3><p>You have process that must communicate over a network of clients and servers.</p><p>A key design goal of micro services is to make services easier to change and maintain by being independently deployed and evolvable.</p><p>A service should be own by one team, and new versions of that service should not require the team to coordinate with other teams. We must expect multiple versions of clients and servers running at the same time and so encoding must be compatible across versions of the API.</p><h4><strong>Web Services</strong></h4><p>There are two main approaches to web services which are <em>REST </em>and<em> SOAP.</em></p><p>Both of them are totally different in terms of philosophy and as such they are often the source of heated debate.</p><p>However REST has gained much more popularity these days as RESTful APIs tends to favour simpler approach involving less tooling and generated code.</p><p>REST is more a design philosophy that emphasises simple data formats, using URLs for identifying resources and using HTTP features for cache control, authentication, and content types negotiation.</p><p>For versioning as you generally update the server first, you at least have to be backward compatible (read old data from clients) for the server and frontward compatible for the client (being able to ignore new data from the server).</p><h4><strong>Remote procedure calls (RPCs)</strong></h4><p>The RPC approach tries to make a network call to another service looks the same as to call a method in within the same process. While this sounds appealing there are some trade-off as a remote call is not the same as an in-process one:</p><ul><li>Network requests are unpredictable (timeout, latency, destination machine unavailable, etc..). You may want to retry a failed request.</li><li>A local function either return a result or throw an exception. If a remote call timed out, your call will return without a result (did the request got through?).</li><li>If you retry a request, what if the request did go through but it is the response that is lost? Then you will perform the action multiple times and you still don’t know if it reaches the other API.</li><li>A local function execution time is roughly the same while a remote call execution time depends due to the network.</li><li>Using local function, you can pass references, pointers to efficiently pass the in-memory objects. With RPC you have to encode your object in bytes which could become an issue with larger objects.</li><li>The client and server may be implemented in different programming languages and so different RPC framework may translate the data type differently.</li></ul><p>The point is, it is a waste of time to try to make your call look like an in process call if it is a remote call as they are really two different things.</p><p>One of the appeals of REST is that it does not try to hide that the call is a network call.</p><p>For versioning, depends on which encoding format, you will use.</p><h4>Does this mean that RPC is going away?</h4><p>Various new libraries have gained lots of popularity such as gRPC which is an RPC implementation built on top of Protobuf. Thrift and Avro came with RPC support included.</p><p>Despite the flaws we talked about, new RPC frameworks have made the effort of making the fact that a remote call is different than an internal one.</p><p>For example, gRPC uses <em>stream </em>where a call is not just one request but a succession of requests and responses. Rest.li and Finagle uses promises to encapsulate asynchronous actions that may fail.</p><h4><strong>Then should I choose REST or RPC?</strong></h4><p>Custom RPC protocols and binary encoding format achieves better <strong>performance </strong>than JSON over REST.</p><p>Aside from that, REST is better to debug and experiment (you can just make a request to use a web browser or curl). REST is well known and can be implemented by any tech stack and there is a vast ecosystem of tools available (servers, caches, load balancers, proxies, firewalls, monitoring, debugging tools, testing tools, etc.).</p><h3>Through asynchronous message passing systems (AMPS)</h3><p>In these systems a client’s request is delivered with low latency to another process. The request is called a message.</p><p>The message is not sent through direct network connection but is instead buffered through a message queue.</p><p>Using a message broker has several advantages:</p><ul><li>Act as a buffer is the recipient is overloaded or unavailable at the time where the message is pushed.</li><li>It can automatically redeliver message to process that has crashed and thus prevent messages from being lost.</li><li>It avoids the sender to have to know the recipient IP:PORT.</li><li>One message can be delivered to multiple recipients (in queue or pub/sub).</li><li>Decouples the publisher and the consumer.</li></ul><p>One trade-off/advantage of this approach is the fact that the communication is generally one-way. The sender does not wait for a response.</p><p>You could wait for a response but this would be done on another channel.</p><p>Message brokers generally don’t enforce a particular data model. So any encoding format can be used.</p><h4>Distributed actor framework</h4><blockquote>The actor model is a programming model for concurrency in a single process. Rather than dealing directly with threads (and the associated problems of race conditions, locking, and deadlock), logic is encapsulated in actors.</blockquote><blockquote>Each actor typically represents one client or entity, it may have some local state (which is not shared with any other actor), and it communicates with other actors by sending and receiving asynchronous messages. Message delivery is not guaranteed: in certain error scenarios, messages will be lost. Since each actor processes only one message at a time, it doesn’t need to worry about threads, and each actor can be scheduled independently by the framework.</blockquote><p>In distributed actor frameworks, this programming model is used to scale applications on multiple nodes. It integrates both the message broker and the actor model in a single framework.</p><p>The message passing system is used whether the actors are on the same node or not. If they aren’t on the same node, the message is transparently encoded and pass to the other node which will then decode it.</p><p>However even though everything is bundled in a single framework, you still have to pay attention to versioning when performing rolling update, both forward and backward compatibility as a new node could talk to an old node and vice versa.</p><h4>Why location transparency works better here than with RPC?</h4><p>This due to the fact that this model assumes that the message can be lost.</p><p>Although latency is higher when actors aren’t on the same node. There is less of a fundamental mismatch between local and remote function call.</p><h3>Conclusion</h3><p>In this part, and the previous one, we talked about data encoding and mode of data flow. The goal was to emphases that with a bit of care, frontward and backward compatibility as well as rolling upgrades is quite achievable.</p><p>When rolling out new services, you have to think about the different versions which will be living side by side, even for a few seconds, and the data that will flow from and to those different services.</p><p>Being able to roll new updates gradually, rolling back in case of failures without breaking all of your services, will ensure a better <strong><em>evolvability </em></strong>of your system by allowing more frequent and smaller release.</p><blockquote>May your application’s evolution be rapid and your deployments be frequent.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab8ebbaf04f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing data intensive application — Chapter 4 — Part 1]]></title>
            <link>https://medium.com/@werckayrton/designing-data-intensive-application-chapter-4-part-1-eb481f82d1bf?source=rss-af5767742e37------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb481f82d1bf</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ayrton Werck]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 13:52:34 GMT</pubDate>
            <atom:updated>2022-12-30T10:42:53.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>DDIA — Data encoding</h3><h3>Encoding</h3><p>When developing an application, changes in data format happens all the time. You add a new field, you modify an existing field etc..</p><p>These change don’t happen instantly in large system. When deploying server-side you could perform a rolling upgrade where new version is deployed a few nodes at a time.</p><p>On the client side you are at the mercy of the user who may not install the update.</p><p>As both old and new code need to coexist, old and new data formats needs to coexist too. To provide good evolvability of your system you need to provide backward and frontward compatibility.</p><p>Backward compatibility is when new code can read data written by old code. It is easier to achieve because the author of the new code know the format of old code.</p><p>Frontward compatibility is when old code can still read data written by new code. This one is trickier because old code must be able to ignore new additions.</p><h3>Formats for encoding data</h3><p>There are at least two representations of the data:</p><ul><li>In memory</li><li>Data written to the network / disk, which needs to be encoded</li></ul><p><strong>Using language specific format</strong></p><p>Language have native way to serialize data in sequence of bytes in memory. It is generally a bad idea to use them to communicate with other system:</p><ul><li>Often tied to a particular programming language.</li><li>The decoding process needs to be able to instantiate arbitrary classes and this is frequently a security hole.</li><li>Versioning is not well handled by these libraries (as they aren’t intended for that)</li></ul><p><strong>Famous data formats</strong></p><p>I will skip parts talking about XML and CSV as they are rarely used.</p><p>JSON popularity is mainly due to its built-in support in web browsers by virtue of being a subset of JS. It also simpler than XML.</p><p>These formats have the advantage to be textual formats and thus human readable but they also have a few problems:</p><ul><li>Ambiguity around encoding of numbers. JSON does not distinguish between integer and floating point nor it specifies a precision.</li><li>Large numbers can be an issue in language as JS.</li><li>Do not support binary strings (bytes without character encoding), people bypass this by encoding to b64. It is hacky and increase data size by 33%.</li></ul><p>Despite these flaws it is good enough for most applications. As long as people agrees on what the format should be it often does not matter how pretty it is or how efficient it is.</p><h3>Binary encoding</h3><p>Even though JSON is less verbose than XML, it still takes more space than binary formats. There are binary encoding for JSON (MesagePack, BSON, BJSON, UBJSON, BISON and Smile).</p><p>Popular binary encoding libraries are Thrift (Thrift) and Protobuf (Google).</p><p>These libraries are based on schemas.</p><p>Thrift offers two protocols:</p><ul><li><strong>BinaryProtocol, </strong>no field names, data uses fields tags referenced by number, 1,2,3</li><li><strong>CompactProtocol </strong>same as binary protocol except it packs the field type and tag in the same bit.</li></ul><p>Protobuf uses a protocol similar to the CompactProtocol.</p><p><strong>How do Thrift and Protobuf handles schema evolution ?</strong></p><p>As schema evolve with time we need to maintain frontward and backward compatibility.</p><p>Field name does not matter but field tags is very important.</p><ul><li><strong>Forward compatible support</strong>. New fields you add have new tag numbers, so old code trying to read new code can simply ignore tags it does not know.</li><li><strong>Backwards compatible support</strong>. As long as each field has a unique tag number, new code can always read old data. Every field after initial deployment must have a default value or be optional else new code won’t be able to accept old code (as the field won’t be set by old code).</li></ul><p>Removing fields is just like adding a field with backward and forward concerns reversed. You can only remove a field that is optional, and you can never use the same tag again.</p><p>What about changing the data type of a field? There is a risk that values will lose precision or get truncated.</p><h3>Binary encodings based on schemas advantages</h3><p>Even though JSON, XML and CSV are widespread, binary encodings based on schemas have multiple advantage:</p><ul><li>Much more compact</li><li>Schemas provide a form of documentation</li><li>Saving schemas in registry allow to check for backward and frontward compatibility issues before deploying.</li><li>For statically typed programing languages, the possibility to generate code that match the schema enables type checking at compile time.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb481f82d1bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing distributed systems — Chapter 3]]></title>
            <link>https://medium.com/@werckayrton/designing-distributed-systems-chapter-3-4571aafa46da?source=rss-af5767742e37------2</link>
            <guid isPermaLink="false">https://medium.com/p/4571aafa46da</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ayrton Werck]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 00:20:40 GMT</pubDate>
            <atom:updated>2022-12-30T10:41:41.151Z</atom:updated>
            <content:encoded><![CDATA[<h3>DDIA — <a href="https://medium.com/@werckayrton/designing-distributed-systems-chapter-3-4571aafa46da?source=your_stories_page-------------------------------------">Storage and retrieva</a>l</h3><p>Storage and retrieval are the foundation of a database.</p><p>Even though you might consider that you don’t need to understand all of the internal mechanism of a database engine, it is still interesting when you had to fine tuning settings of your DB.</p><p>The book focuses on two families of storage engines which are <em>log structured </em>and <em>page oriented</em> (such as B-Tree).</p><h3>Indexes</h3><p>To efficiently find the key in the database we need a particular data structure: <em>indexes.</em></p><p>Indexes speed up reads and database generally allows you to setup multiple index. Indexes can be added or removed without modifying the content of your data. This is because indexes are an <em>additional </em>data structure.</p><p>If indexes speed up reads, why not put indexes on every key?</p><p>Because indexes needs to be updated when you create new data, adding more index will slow down your writes. This is why we don’t index everything.</p><h3>Hash indexes</h3><p>Hash indexes are like dictionaries.</p><p>If we consider that our storage is an append only then simplest indexing strategy is to have a hash map in memory where each key map to an offset to the data file.</p><p>When a new key value is updated or created, it means a new file has been created on disk. So to update the value in the hash map we only change the offset that points to the data file.</p><p>Bitcask uses that simple strategy, the only requirement is that all keys fit into the RAM. If the values are too big to fit in they can still be read from the disk, and if the filesystem has the file in cache then no I/O are needed.</p><p><strong>How do we avoid running out of space?</strong></p><p>As we are in an append only system how would we prevent running out of disk space if our application is write heavy?</p><p>A common strategy is to use compaction.</p><p>To do that we would have to write new changes to segment file and then close these segments when they reach a certain size.</p><p>Once they are close we can run a process to detect duplicate keys and remove old values to keep only the most recent ones.</p><p>In practice there are several details needed to make it work:</p><ul><li><em>File format</em>: it is faster to use a binary format that encodes the length of a string in bytes followed by the raw string</li><li><em>Deleting records</em>: to delete a key and associated value, add a special record to mark the data (sometimes called a tombstone). Then when segments are merged the merging process can ignore values of the key.</li><li><em>Crash recovery</em>: in case of a restart you would have to read all of the segment files to rebuild the hash map which can be long and painful. Bitcask solves it by taking snapshot of segment’s hash map to disk to speed up the process.</li><li><em>Partially written records</em>: if the process crash when writing to the disk then data would be loss. To prevent that, Bitcask includes a checksum to detect corrupted data file.</li><li><em>Concurrency control</em>: logs are appended in a sequential manner so one common implementation choice is to have one writer thread. As files are immutable they can be read concurrently by multiple threads.</li></ul><p><strong>Why just not updating the file in place?</strong></p><p>Appending and merging are generally much faster than <a href="https://stackoverflow.com/questions/2100584/difference-between-sequential-write-and-random-write">random writes</a> because they are sequentially write operations.</p><p>Concurrency is also better as you don’t have to worry if the process crash in the middle of an update, leaving you with both old and new data.</p><p>Merging old segments avoids the problem of data files getting fragmented over time.</p><p><strong>Hash tables limitations</strong></p><p>The hash table must fit in memory. If the number of key excess the memory then you would have to use an on disk implementation which would not perform well as it involves lots of random access I/O. Hash collisions would also be harder to handle.</p><p>Range queries are inefficient. If you want to query item001…item999, you would have to scan every key in the hash maps.</p><h3>SSTables</h3><p>We add a requirement to the segment file, keys in a segment file must be sorted.</p><p>This format is called <em>Sorted String table.</em></p><p>It has many advantages over the previous implementation:</p><ul><li>Merging segments is simple and efficient (we can use algorithms like <em>mergesort</em>). When multiple segments contain the same key, we can keep the value from the most recent segment and discard the values in older segments.</li><li>You no longer need to keep an index of all the keys in memory. For a key like handiwork, when you know the offsets for the keys handback and handsome, you know handiwork must appear between those two. You can jump to the offset for handback and scan from there until you find handiwork, if not, the key is not present. You still need an in-memory index to tell you the offsets for some of the keys. One key for every few kilobytes of segment file is sufficient.</li><li>Since read requests need to scan over several key-value pairs in the requested range anyway, it is possible to group those records into a block and compress it before writing it to disk.</li></ul><p><strong>How to maintain order when writes are done in any order?</strong></p><p>Maintaining an order in memory is easier as there exists data structure such as AVL tree or red black tree. You can insert key in any order and read them ordered.</p><p>The new algorithm could looks like something like that:</p><p>A new entry is added in memory via the tree data structure (often called a <em>memtable</em>). When the memtable reaches a certain size it is flushed to disk as an SSTable file. The SSTable file become the most recent segment of the table. While flushing to disk, writes can continues in memory to a <strong>new </strong>memtable instance.</p><p>Read orders starts with the in memory memtable, then the most recent segment file, then older ones.</p><p>From time to time run a merge and compact process.</p><h3>LSM-tree</h3><p>You may be wondering what happens if the database crash with data still in memory.</p><p>If the memtable was not persisted to disk then the data is lost. To workaround it we write a log on disk for each in memory write.</p><p>The write log is an append only operation and is not sorted which makes it really fast. It does not need to be sorted as its role is to restore the memtable in memory in case of a crash.</p><p>When the memtable is persisted to disk the write logs can be discarded.</p><p>This indexing structure is called <strong>LSM tree (Log-Structured Merge-Tree).</strong></p><p>LSM-tree algorithm can be slow when looking up keys that don’t exist in the database. To optimize this, storage engines often use additional <em>Bloom filters</em> (a memory-efficient data structure for approximating the contents of a set).</p><h4>Who uses that?</h4><p>The algorithm described here is essentially what is used in LevelDB and RocksDB, key-value storage engine libraries that are designed to be embedded into other applications. Among other things, LevelDB can be used in Riak as an alternative to Bitcask. Similar storage engines are used in Cassandra and HBase , both of which were inspired by Google’s Bigtable paper (which introduced the terms SSTable and memtable).</p><h3>B-Tree</h3><p>Even though LSM tree are gaining tractions, B-Tree is the most common type of index in almost all relational and in many NoSQL databases.</p><p>B-Tree like SSTables keep values sorted by key. However they differs in the way they organize the data.</p><p>The log-structured indexes break the database down into variable-size <strong>segments</strong>, and always write a segment sequentially.</p><p>B-trees break the database down into <strong>fixed-size pages</strong>, traditionally 4 KB in size (sometimes bigger), and read or write one page at a time.</p><p>B-trees works with pages, it starts with a root page and search from there. The pages contains key and ref to child pages.</p><p>To update the value of a key, find the leaf page containing the key, update the value and persist the page back to disk.</p><p>To add a new key, find the page and insert it. If no space are left in the page then the page is split in two full page and the parent page is updated. This allows the B-tree to remain <strong>balanced </strong>and to ensure that depth of the b-tree is always O(log N).</p><p><strong>Update in place</strong></p><p>Contrary to LSM-tree, the page is updated in place. A basic underlying operation of a B-tree is to overwrite a page on disk.</p><p>When your operation requires to update multiple pages at the same time, if the database crashes, you could end up with a corrupted index.</p><p>In order to prevent that, a common strategy is to include a <em>Write ahead log (WAL).</em></p><p>A WAL also known as a redo log, is an append only file where every B-trees operations <strong>must </strong>be logged before being executed. It is used when the DB crashes to restore the B-tree to a consistent state.</p><p>Careful concurrency control is required if multiple threads are going to access the tree at the same time, typically done protecting the tree internal data structures with <em>latches</em> (lightweight locks).</p><p>This was not an issue with LSM tree as the merging process is done in background and from time to time it swaps data atomically.</p><p>As b-trees are quite mature, there are lots of optimizations that has been developed to alleviate some of these issues.</p><h3>How to choose between B-Tree and LSM-Tree?</h3><p>As a rule of thumb, LSM-Tree are considered more performant for writes and B-Tree are supposedly more performant for reads.</p><p>Reads are typically slower on LSM-tress as they have to check several different data structures and SSTables at different stages of compaction.</p><p>However benchmarks are inconclusive. It depends a lot on the data and the system which will use the DB. It is advised to benchmark with your own use-case to make a decision.</p><p>Advantages of LSM-trees:</p><ul><li>LSM-trees are handle higher write throughput than B-trees. This is due to have lower <strong>write amplification</strong>(a write to the database results in multiple writes to disk). The more a storage engine writes to disk, the fewer writes per second it can handle.</li><li>LSM-trees can be compressed better, and thus often produce smaller files on disk than B-trees. B-trees tend to leave disk space unused due to fragmentation.</li></ul><p>Downsides of LSM-trees:</p><ul><li>Compaction process can sometimes interfere with the performance of ongoing reads and writes. B-trees can be more predictable. The bigger the database, the the more disk bandwidth is required for compaction. Compaction cannot keep up with the rate of incoming writes, if not configured properly you can run out of disk space.</li><li>On B-trees, each key exists in exactly one place in the index. This offers strong transactional semantics. Transaction isolation is implemented using locks on ranges of keys, and in a B-tree index, those locks can be directly attached to the tree.</li></ul><h3>Keeping everything in memory</h3><p>Disks have two significant advantages: they are durable, and they have lower cost per gigabyte than RAM.</p><p>As the cost of RAM becomes cheaper and cheaper, also considering that the dataset aren’t that big, in-memory databases start to be more popular.</p><p>Some like <em>memcached </em>are designed to be used for cache only. If the machine restart the data is lost. However others aim for durability.</p><p>When an in memory database need to rebuild its state, it can do it either from disk, from network from another replica.</p><p>Despite that state is written to disk it is still an in memory DB as the reads are only made from the RAM and the writes to disk are merely append logs to rebuild the database when need.</p><p>When looking to in memory databases, we must pay attention to the durability policy defined by the vendor. For example Redis and Couchbase provide weak durability by writing changes asynchronously.</p><p>Example of vendors: VoltDB, MemSQL</p><p><strong>Why in memory DB are more performant?</strong></p><p>You may think that the response is obvious:<br>“Because it’s in memory it is faster than reading from disk”</p><p>Even though that’s not wrong, if you have enough memory, the OS will keep recently used disk blocks in memory to speed read access so you would already be leveraging the RAM.</p><p>The reason they are more performant is because they avoid the overhead of encoding in-memory data structure in a form that can be written to disk.</p><p>Another area where in-memory DB shines, is that they can provide data model which are difficult to provide with data written on disk (e.g.: priority queue, sets).</p><p>If your indexes can all fit in memory then some approach can be used to store bigger than memory datasets. For example using LRU (least recently used) you could evict data which the least used and free up space in the ram.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4571aafa46da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing data intensive application — Chapter 2]]></title>
            <link>https://medium.com/@werckayrton/designing-data-intensive-application-chapter-2-ee8f80f70aef?source=rss-af5767742e37------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee8f80f70aef</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ayrton Werck]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 16:20:06 GMT</pubDate>
            <atom:updated>2022-12-30T10:41:00.026Z</atom:updated>
            <content:encoded><![CDATA[<h3>DDIA — <a href="https://medium.com/@werckayrton/designing-data-intensive-application-chapter-2-ee8f80f70aef?source=your_stories_page-------------------------------------">Data Models and Query Languages</a></h3><p>Most applications are built by layering one data model on top of another. For each layer, the key question is: how is it represented in terms of the next-lower layer?</p><h3>Relational Model vs Document Model</h3><h3>Relational</h3><p>The roots of relational databases lie in business data processing.</p><p>The use cases were mainly transaction and batch processing (e.g.: adding money to a bank account or reporting)</p><p>Relational DBs are still very popular and used a lot. They are able to pass through time due to their ability to generalize well beyond the original scope.</p><h3>Not Only SQL</h3><p>Even though relational DBs performs well and are quite versatile, there are points on which they can be improved.</p><p>As such NoSQL responds to different needs:</p><ul><li>Greater and easier <strong>scalability</strong></li><li>Preference for <strong>free and open source software</strong></li><li><strong>Specialized </strong>query operations</li><li>More <strong>dynamic </strong>and <strong>expressive </strong>data model</li></ul><h3>Data model representation</h3><p>The criticism for SQL comes from the fact that objects in code do not match with relational tables. As such a translation layer must be set in place to convert models from the database to a model from the domain.</p><p>This is called <strong>impedance mismatch</strong>.</p><p><strong>Advantages of a JSON model</strong></p><p>Document DB offers <strong>JSON </strong>representation of the data which is considered as <strong>reducing </strong>the impedance mismatch between the data storage and the application code.</p><p>This <strong>lack of a schema</strong> is cited as an advantage.</p><p><strong>JSON </strong>has a better locality than relation models. To build a model from a relational DB you have to query multiple tables whereas in a JSON model the data is located in the same document, thus one query is needed.</p><h3>Data flexibility</h3><p>SQL DBs have strict data schema which is validated on write when persisting data as opposed documenting DB where schema is checked on read.</p><p>We say that relational DB has <strong>schema on write</strong> and NoSQL DB have <strong>schema on read.</strong></p><p>Issues with schema on red is the fact that there is no guarantee when querying the data that the model you want matches the model in the database.</p><h3>Querying Data</h3><p>Document DB has weak supports for join when many-to-one or many-to-many relation ships are needed. Most of the time the join must be performed in application code.</p><p>Even though your app fits well in a join-free document model at first, data has a tendency of becoming more interconnected as features are added to applications.</p><p>SQL DBs can leverage the “query optimizer” which will optimize a query based on the indexes. It will automatically select the best access path to a result. Thus you don’t need to change your query when adding new features / columns.</p><h3>How to choose then ?</h3><p>There are no clear answers to that as it depends heavily on the business case.</p><p>There are many differences to take into account in addition to the data model. The concurrency and ability to handle fault (being fault tolerant) are also properties that must be considered.</p><p>From a data model point of view, if your data looks like a tree of one too many relationships and you will load the whole tree during queries then NoSQL is probably a good option.</p><p>If you were to do it in an SQL fashion, you would have to use <strong>shredding </strong>(converting a document-like into multiple tables). This technique can lead to cumbersome schemas and unnecessarily complicated application code.</p><p>If your data implies a lot of many-to-many relations ships, then a Graph Model may be more appropriate.</p><h3>Convergence of both models</h3><p>PostgreSQL does support JSON documents. RethinkDB supports relational-like joins in its query language and some MongoDB drivers automatically resolve database references. Relational and document databases are becoming more similar over time.</p><h3>What about Graph data model?</h3><p>Even though the relational data model can handle many-to-many relationships, if your application contains a lot of them, then you should consider a graph data model.</p><p><strong>What is a Graph?</strong></p><p>A graph consists of two kinds of objects:</p><ul><li>Vertices (aka nodes or entities)</li><li>Edges (relationships between vertices)</li></ul><p><strong>Advantages of graph</strong></p><ul><li>Well-known algorithms can operate on these graphs, like the shortest path between two points, or popularity of a web page.</li><li>Promote evolvability as it is very flexible.</li><li>Works with non-homogenous set of data</li></ul><blockquote>Facebook maintains a single graph with many different types of vertices and edges: vertices represent people, locations, events, check-in, and comments made by users; edges indicate which people are friends with each other, which check-in happened in which location, who commented on which post, who attended which event, and so on.</blockquote><h3>How to Model a Graph</h3><p>There are several ways of structuring and querying the data. The <em>property graph</em> model (implemented by Neo4j, Titan, and Infinite Graph) and the <em>triple-store</em> model (implemented by Datomic, AllegroGraph, and others).</p><p>Each vertex consists of:</p><ul><li>Unique identifier</li><li>Outgoing edges</li><li>Incoming edges</li><li>Collection of properties (key-value pairs)</li></ul><p>Each edge consists of:</p><ul><li>Unique identifier</li><li>Vertex at which the edge starts (<em>tail vertex</em>)</li><li>Vertex at which the edge ends (<em>head vertex</em>)</li><li>Label to describe the kind of relationship between the two vertices</li><li>A collection of properties (key-value pairs)</li></ul><h3>Query language of a Graph</h3><p>Cypher, SPARQL, and Datalog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee8f80f70aef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing data intensive application— Chapter 1]]></title>
            <link>https://medium.com/@werckayrton/designing-data-intensive-application-chapter-1-645aa785c684?source=rss-af5767742e37------2</link>
            <guid isPermaLink="false">https://medium.com/p/645aa785c684</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Ayrton Werck]]></dc:creator>
            <pubDate>Sun, 26 Jun 2022 17:27:12 GMT</pubDate>
            <atom:updated>2022-06-26T17:27:12.015Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This article is the first of a list intended to summarize chapters from the famous Design Data Intensive Applications from Martin Kleppmann.</p><p>This book is intense and has lots of information.</p><p>After reading a few chapters it became obvious that in order to retain anything I would have to do some personal work (such as these articles).</p><p>More info: <a href="https://ardalis.com/learning-consumption-creation/">https://ardalis.com/learning-consumption-creation/</a></p><h3>Properties of a good distributed system</h3><p>Designing a distributed system is hard. It involves many parts (data, services, storage, networking, scale…), making each decision a struggle as it can have consequences on many blocks composing our system.</p><p>To help us make such decisions we must keep in mind these three tenets: <strong>Reliability</strong>, <strong>Scaleability</strong>, <strong>Maintainability</strong>.</p><h3>Reliability</h3><p>The system must be able to perform and offer services even in case of trouble such as human error or hardware failures.</p><p>A bit of vocabulary:</p><ul><li>Faults, things that can go wrong, one component of the system which deviates from its spec.</li><li>Failure, the system as a whole go down and no service is offered to the user anymore.</li><li>Systems that can cope with faults are called fault-tolerant or resilient.</li></ul><p>Systems which will never encounter a fault does not exist, as such we always must prepare and design in a way that will allow us to be resilient to such faults in order to prevent failures.</p><p>A good way to test the system to see if it is resilient is to mimic what Netflix does with Chaos Monkey testing.</p><h3><strong>Scalability</strong></h3><p>The system must be able to provide service with increasing load.</p><p>A load can be more concurrent users or it can be an increase volume of data being processed.</p><p>It is important to understand what is the meaning of load in your system to better find solutions to support that increase of Load.</p><p>Load can be, for example, the number of requests per second to a web server, or the number of reads/writes to a database.</p><p><strong>Performance</strong></p><p>Performance meaning differs from a system to another.</p><p>For a web service this can be described by the response time of the server.</p><p><strong>Latency vs Response Time</strong></p><ul><li>Response time is what the client sees (network delay, actual time to process the request).</li><li>Latency is the time the request wait before being processed (it is said to be latent).</li></ul><p><strong>How to measure performance?</strong></p><p>To measure performance using Response time, it is better to use percentile.</p><p>For example, taking the median of response time corresponds to the p50 percentile. 50% of users wait less than X where the other 50% wait more than X.</p><p>To find bad outliers we can check the p95, p99 or even p99.9 also called p999.</p><p>So if the p95 of requests is 1.5 seconds it means that 95 out of 100 requests take less than a 1.5 second and so 5 take more than 1.5 seconds.</p><p><strong>When measuring response time, it has to be done client side.</strong></p><p>Because a server can process only a maximum number of requests in parallel.</p><p>So if your latency is high (your request stay latent for a long time) but your server process request rapidly, the client will have to wait for the latency+process time before receiving a response.</p><p>It actually takes a low number of requests to hold up the subsequent process of other requests.</p><p>This effect is known as <strong>head-of-line blocking</strong>.</p><p><strong>Strategies</strong></p><p>To scale efficiently we have two main strategies.</p><p>Either vertically (adding resources to the server) or horizontally (distributing loads to different machines).</p><h3>Maintainability</h3><blockquote>Every legacy system is unpleasant in its own way, and so it is difficult to give general recommendations for dealing with them.</blockquote><p>When thinking of maintainability, we must focus on three primary points:</p><ul><li>Operability, (make it easy for operations to keep the system run smoothly).</li><li>Simplicity, (make it easy for new engineers to understand the system by removing as much as possible complexity from the system).</li><li>Evolvability, (make it easy for engineers to make changes to the system in the future, adapting it for unanticipated use cases as requirements change).</li></ul><p>Maintainability has many facets, but in essence it’s about making life better for the engineering and operations teams who need to work with the system. Good <strong>abstractions </strong>can help reduce complexity and make the system easier to modify and adapt for new use cases. Good operability means having good <strong>visibility </strong>into the system’s <strong>health</strong>, and having effective ways of <strong>managing </strong>it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=645aa785c684" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Swift — Currying]]></title>
            <link>https://medium.com/nuglif/functional-swift-currying-d398a73bf1ed?source=rss-af5767742e37------2</link>
            <guid isPermaLink="false">https://medium.com/p/d398a73bf1ed</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[currying]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ayrton Werck]]></dc:creator>
            <pubDate>Mon, 05 Nov 2018 14:13:31 GMT</pubDate>
            <atom:updated>2018-11-13T21:11:26.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ye_BIjKMgWUeXPECiBoeEQ.png" /></figure><h3><strong>Functional Swift — Currying</strong></h3><p>While working with Swift I delved deeper and deeper in the functional programing environment.</p><p>Many of the techniques used in other programming languages such as Python or Haskell are available in swift.</p><p>Today I’d like to present you one of these called currying.</p><h3><strong>Definition</strong></h3><p>Swift is an amazing programming language that takes advantage of functional programing.</p><p>One of the main benefits of functional programing is that functions are high order citizens which means that functions in swift can do one of the following:</p><ul><li>Takes one or more functions as arguments</li><li>Return a function as an argument</li></ul><p>Recently I discovered a well-known technique among functional programmer named Curry.</p><p>Currying is used to break down a function that has multiple arguments into a series of functions that take part of the arguments.</p><p>This technique becomes quite useful when you want to improve readability and re usability of your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*oBQP-JjWNF-WQ6uOiPFjLw.png" /><figcaption>Currying</figcaption></figure><h3>Implementation</h3><p>The function looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf710dc41183630fedac5c68d4026868/href">https://medium.com/media/bf710dc41183630fedac5c68d4026868/href</a></iframe><p>As you can see curry is a simple <strong>function.</strong></p><p>It takes a <strong>function</strong> as an argument (<strong>fn</strong>)<strong> </strong>and first returns a <strong>function </strong>that takes the first argument of the <strong>function </strong>passed in parameters to curry (here <strong>A</strong>):</p><ul><li>(a: A) -&gt; (B) -&gt; C</li></ul><p>It then returns a <strong>function </strong>that takes the second argument of the <strong>function</strong> passed to curry (here <strong>B</strong>):</p><ul><li>(b: B) -&gt; C</li></ul><p>Finally, the <strong>function</strong> passed as an argument is called using parameters <strong>A </strong>and<strong> B</strong>:</p><ul><li><strong>fn</strong>(a,b)</li></ul><p>It is worth noticing that the function <strong>fn </strong>is <strong>computed</strong> only when the last argument is passed to the curried method.</p><h3>Use cases</h3><p>There are cases where this method can be useful, one of them is when you want to make an existing method more convenient or reusable to use:</p><p>Let’s take the following log methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87a5e4195de731ab8ab9920748db297f/href">https://medium.com/media/87a5e4195de731ab8ab9920748db297f/href</a></iframe><p>Calling it with two arguments can become tedious, using curry we can make it reusable and more explicit without creating a new function that encapsulates the arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0a6805b047bf62eebb2bccce73e6673/href">https://medium.com/media/e0a6805b047bf62eebb2bccce73e6673/href</a></iframe><p>Taking full advantages of high order functions, we can break down logMessage and create a variable that is a function which takes a log message as parameters and then log it on the debug level.</p><p>Another use is to take advantage of functional methods such as <strong>map</strong>, <strong>forEach</strong> etc.</p><p>Let’s take the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fac7b25a4a6672578e5b1e7dd17493a/href">https://medium.com/media/4fac7b25a4a6672578e5b1e7dd17493a/href</a></iframe><p>As you can see using currying, it is quite easy to partially apply any methods.</p><h3><a href="https://github.com/RxSwiftCommunity/RxSwiftExt/blob/master/Source/RxSwift/fromAsync.swift"><strong>Bonus</strong></a></h3><h4>(<a href="https://medium.com/u/341500d28721">Vincent Pradeilles</a> showed this use case of currying at a CocoaHeads where I was present.)</h4><p>If you are using RxSwift or planning to use it, you may have wondered how to migrate your asynchronous code that uses completionBlock to a sequence of Observable.</p><p>Refactoring all of your code base just to get observable instead of (completionBlock / success and fail block) is generally not an option.</p><p>Using curry and extensions, you can achieve it with little to no code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c3dc559b781885142542b85678db44d/href">https://medium.com/media/9c3dc559b781885142542b85678db44d/href</a></iframe><p>The first fromAsync method takes as an argument a function that takes a completionBlock as sole parameters. It is the method that will handle the conversion to an <strong>Observable</strong>.</p><p>The other two methods are works exactly the same except that they use currying to break down the parameters and return the first <strong>fromAsync</strong> methods.</p><p>The first one is used to convert methods that have one argument and a completionBlock.</p><p>The last one is used to convert methods that takes two arguments and a completionBlock.</p><h3><strong>Example</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b5f0b7a43216dfff0a1bddd2aa650ed/href">https://medium.com/media/3b5f0b7a43216dfff0a1bddd2aa650ed/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d398a73bf1ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nuglif/functional-swift-currying-d398a73bf1ed">Functional Swift — Currying</a> was originally published in <a href="https://medium.com/nuglif">Nuglif</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>