<?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 Omar Rayward on Medium]]></title>
        <description><![CDATA[Stories by Omar Rayward on Medium]]></description>
        <link>https://medium.com/@orayward?source=rss-2596e24c8ffb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JrEUfcAFIeRrxxsjCT47-Q.png</url>
            <title>Stories by Omar Rayward on Medium</title>
            <link>https://medium.com/@orayward?source=rss-2596e24c8ffb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:04:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@orayward/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[Breaking Free From the ORM: Replacing Database Queries]]></title>
            <link>https://medium.com/building-the-system/breaking-free-from-the-orm-replacing-database-queries-3e8c4820d697?source=rss-2596e24c8ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e8c4820d697</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Omar Rayward]]></dc:creator>
            <pubDate>Mon, 01 Oct 2018 13:30:36 GMT</pubDate>
            <atom:updated>2018-10-01T13:30:36.779Z</atom:updated>
            <content:encoded><![CDATA[<h4>The final step to remove the ORM from our programs</h4><blockquote>TL;DR, Make your life easier by configuring data types transformations and data formatting from data going in and out of the database.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*XUtRBh0VlgEyCIpyFuGxag.png" /></figure><p>In previous articles, we looked at <a href="https://medium.com/system-is-asset-code-is-liability/dont-be-a-sucker-and-stop-using-orms-190add65add4">why object relational mapping is a detrimental construct</a>, how to <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-decoupling-database-migrations-e6e53d144cab">decouple database migrations</a> from the ORM and how to <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-replacing-connection-handling-25466845ff9">handle database connections</a> in our program.</p><p>An ORM usually combines three competencies in one. So, when we remove the ORM, we have to replace:</p><ol><li>Database migrations</li><li>Database connection handling</li><li>Database queries</li></ol><p>In this fourth and final part of the series, we will explore how to manage database queries without relying on an ORM.</p><h3><strong>Database read, write and other operations</strong></h3><p><em>In this article, we’ll use python and PostgreSQL to illustrate the some of the concepts.</em></p><p>We now have the necessary components in place to write the database queries required to implement our application’s business logic. We also have access to use all database functionality without a mediocre adapter(ORM).</p><p>Once we start using raw SQL queries, we realize that we have shifted from the <a href="https://medium.com/system-is-asset-code-is-liability/dont-be-a-sucker-and-stop-using-orms-190add65add4">complexity of dealing with the ORM</a> to the complexity involved in formatting the data going back and forth between our program and the database. The latter complexity is now much easier to understand, solve and debug.</p><p>When formatting data back and forth from the database these are the two main requirements:</p><h4><strong>1. Appropriate data types transformations between application and database</strong></h4><p>Every project has its own requirements. Here, some of the most common requirements that we usually have when working with Python and PostgreSQL:</p><ul><li>UUIDs as unique identifiers in the database should be properly mapped to a UUID Python data type.</li><li>PostgerSQL datetimes should be mapped to the Python datetimes using the arrow library.</li><li>The jsonb PostgreSQL data type should be mapped to a Python dictionary.</li></ul><p>To achieve those transformations we need to configure the database connector to handle those data types correctly. When using psycopg2 as the Python library to connect to PostgreSQL:</p><pre><strong>import </strong>psycopg2.extensions<br><strong>from </strong>psycopg2.extras <strong>import </strong>Json</pre><pre><strong>def </strong>cast_date(value, conn):<br>    <strong>return </strong>arrow.get(value)</pre><pre># Cast datetime to Arrow objects<em><br></em>NewDate = psycopg2.extensions.new_type(<br>    psycopg2.extensions.PYDATETIMETZ.values, <br>    <strong>&#39;DATE&#39;</strong>, <br>    cast_date<br>)</pre><pre># Handles datetimes transfo<br>psycopg2.extensions.register_type(NewDate)</pre><pre># Handles UUID transformations<br>psycopg2.extras.register_uuid()</pre><pre># Handles jsonb to/from Python dictionary transformations<br>psycopg2.extensions.register_adapter(dict, Json)</pre><h4><strong>2. Manageable data format coming back from the database</strong></h4><p>The data usually comes back from the database as a collection of tuples. Each element of the tuple refers to a different field in the database. A collection of dictionaries where each key refers to the database column name and each value to the respective column’s value is a more manageable data format.</p><p>When using psycopg2 this can be achieved by passing a specific cursor option:</p><pre>from psycopg2.extras import RealDictCursor</pre><pre>with conn.cursor(cursor_factory=RealDictCursor) as cursor:<br>    cursor.execute(&quot;&quot;&quot;SELECT id FROM users where id=1&quot;&quot;&quot;)<br>result = cursor.fetchall()</pre><pre>assert result == [{‘id’: 1}]</pre><h4><strong>Plain Data vs. Objects</strong></h4><p>We now understand how to do database migrations, connect to the database and query the database without using an ORM. At this point, we receive plain data from the database and must decide how to treat that data. Communities around languages such as Java, Ruby or Python favor placing the data in objects. Other communities such as the Clojure community favor plain data structures.</p><p>By removing the ORM from our system we are now able to have these architecture conversations within the team, which was not possible before because the decision was already made by the ORM.</p><h3>Building the system</h3><p>With this final post, we conclude the series on “Breaking free from the ORM”. Over the course of these four articles, we have discussed reasons regarding why to remove the ORM dependency from our programs. We have also explored what tools and programming techniques we need to use to eliminate the ORM from our programs.</p><p>Warren Buffet and Charlie Munger run Berkshire Hathaway. Over the years, they have achieved slightly below average results on the ‘good’ financial years; and, done great on the ‘bad’ financial years. This has led them to realize tremendous financial success.</p><p>Breaking free from the ORM should yield similar results. In very straightforward cases, removing the ORM undoubtedly creates more work. In obscure cases, where “shit hits the fan” (sooner or later, it always does), not using an ORM will yield high dividends. This can largely be attributed to reducing the complexity in the system that comes from using an ORM and having code that is better understood and easier to debug.</p><p>By removing the ORM from our systems we are improving <strong>the system</strong> by increasing understanding and enhancing control of how the data tier is managed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e8c4820d697" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-the-system/breaking-free-from-the-orm-replacing-database-queries-3e8c4820d697">Breaking Free From the ORM: Replacing Database Queries</a> was originally published in <a href="https://medium.com/building-the-system">Building the system</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Free From the ORM: Replacing Connection Handling]]></title>
            <link>https://medium.com/building-the-system/breaking-free-from-the-orm-replacing-connection-handling-25466845ff9?source=rss-2596e24c8ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/25466845ff9</guid>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Omar Rayward]]></dc:creator>
            <pubDate>Fri, 24 Aug 2018 19:10:52 GMT</pubDate>
            <atom:updated>2018-10-01T13:32:47.188Z</atom:updated>
            <content:encoded><![CDATA[<h4>Handle performant connections to the database</h4><blockquote>TL;DR, Understand the threading model running your program when reusing database connections.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*sZ4AeXZUQVPdhY0DNX-IIA.png" /></figure><p>In previous articles, we looked at <a href="https://medium.com/system-is-asset-code-is-liability/dont-be-a-sucker-and-stop-using-orms-190add65add4">why object relational mapping is a detrimental construct</a>, and how to start breaking free of the ORM by first <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-decoupling-database-migrations-e6e53d144cab">decoupling database migrations</a>.</p><p>An ORM usually combines three competencies in one. So, when we remove the ORM, we have to replace:</p><ol><li>Database migrations</li><li>Database connection handling</li><li>Database queries</li></ol><p>In this article, we’ll explore how to handle connecting to the database. In the next and final article, we’ll look at how to <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-replacing-database-queries-3e8c4820d697">implement database queries</a> without using the ORM.</p><h3><strong>Handling Database Connection</strong></h3><p><em>The scope of this article isn’t to explain how to connect from every potential application to every potential database. Here, we are only exploring how to connect from a Python program to a PostgreSQL database.</em></p><p>No matter how we connect to the database, we always have to take into consideration two things:</p><p><strong>1. What performance bottlenecks are there when connecting from our program to the database?</strong></p><p>In the case of PostgreSQL, one bottleneck is establishing a connection to the database. Since establishing the connection takes so much time, we want to reuse connections as much as possible. That way, we don’t have to open a new connection with every database query.</p><p><strong>2. Does the threading model running our program affect performance when querying the database?</strong></p><p>The processes running our programs can be single-threaded or multi-threaded.</p><h4><strong><em>Single Threaded</em></strong></h4><p>In this case, each process starts a different instance of the application. Each instance of the application opens a database connection, and this will be reused for different requests. There will never be concurrent requests since each process is running on a single thread.</p><h4><strong><em>Multiple Threads</em></strong></h4><p>In this case, each process has multiple threads, therefore, some code may be shared between threads. If the database connection is shared, then database queries will slow down since every query will go through the same connection.</p><p>For this, it’s useful to have a pool of database connections, and just use one of them for each transaction. Once each database transaction is finished, the connection is placed back to the pool. This way, even though the pool is shared, there’s no database connection shared between threads.</p><p>Here is some code:</p><pre># db_connection.py<br>from psycopg2.pool import ThreadedConnectionPool<br>from contextlib import contextmanager<br>min_connections = 1<br>max_connections = 10</pre><pre>dsn = ‘postgresql://...’<br>psql_connection_pool = ThreadedConnectionPool(min_connections, max_connection, dsn=dsn)</pre><pre>@contextmanager<br>def connection():<br>    try:<br>        connection = psql_connection_pool.getconn()<br>        yield connection<br>    finally:<br>        psql_connection_pool.putconn(connection)</pre><pre># feature.py<br>from db_connection import connection</pre><pre>def format_user(user):<br>    return # do something</pre><pre>with connection() as conn:<br>    with conn.cursor() as cursor:<br>        cursor.execute(&quot;&quot;&quot;SELECT * FROM users&quot;&quot;&quot;)<br>        users = [format_user(x) for x in cursor.fetchall()]<br>return users</pre><h3>Building the system</h3><p>In this third article of a four-part series, we’ve covered the need to understand how we connect to our database. This part of the program is usually hidden deep in the guts of the ORM.</p><p>To performantly connect to the database, we need to reuse the connection between transactions, without using that same connection in different threads at the same time.</p><p>Once we do that, we’ll have a better understanding of the system that we’re creating, and how its different parts — in this case, the application and database — communicate through a common interface.</p><p>Next, we’ll cover practical advice on how to deal with <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-replacing-database-queries-3e8c4820d697">database queries</a> to break free from ORM once and for all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25466845ff9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-the-system/breaking-free-from-the-orm-replacing-connection-handling-25466845ff9">Breaking Free From the ORM: Replacing Connection Handling</a> was originally published in <a href="https://medium.com/building-the-system">Building the system</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Free From the ORM: Decoupling Database Migrations]]></title>
            <link>https://medium.com/building-the-system/breaking-free-from-the-orm-decoupling-database-migrations-e6e53d144cab?source=rss-2596e24c8ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6e53d144cab</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Omar Rayward]]></dc:creator>
            <pubDate>Fri, 24 Aug 2018 16:22:42 GMT</pubDate>
            <atom:updated>2018-10-01T13:32:10.000Z</atom:updated>
            <content:encoded><![CDATA[<h4>Defining expectations from a database migration system without an ORM</h4><blockquote>TL;DR, Removing the database lifecycle from your application lifecycle will reduce the complexity in the system.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*VNOclwbsWwwcmkE8j-Fj8A.png" /></figure><p>In our previous article, we explored <a href="https://medium.com/system-is-asset-code-is-liability/dont-be-a-sucker-and-stop-using-orms-190add65add4">why the ORM is a detrimental construct</a>. When we seek to reduce complexity by removing it, we need to replace three competencies bundled into one:</p><ol><li>Database migrations</li><li>Database connection handling</li><li>Database queries</li></ol><p>In this article, we’ll focus on decoupling database migrations. In future articles, we’ll look at <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-replacing-connection-handling-25466845ff9">connection handling</a> and <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-replacing-database-queries-3e8c4820d697">database queries</a>.</p><h3><strong>Requirements for the database migration system</strong></h3><ul><li><strong>Native scripting: </strong>Databases have a rich set of features accessible by their scripting language. There should be no need to learn a different DSL (<a href="https://en.wikipedia.org/wiki/Domain-specific_language">Domain-specific Language</a>) to make changes to our database.</li><li><strong>Proper order of execution: </strong>The system should enforce the application of database changes in the same predetermined order every time these changes run.</li><li><strong>Rollback:</strong> We always think about database migrations as a means to evolve the database, but sometimes we screw up and need to “rollback” to a previous version. We need this functionality in our database migration system.</li><li><strong>No dependencies on the application:</strong> ORMs are usually embedded within the language or framework that we use when writing our back-end applications (e.g., Django, Ruby on Rails, etc..). For our database migration system, we want to dissolve the bindings between the tools we use to write the application logic and the tools we use to manage our migrations. This allows us to manage the database lifecycle independently of our application lifecycle. Then we’ll be able to deploy database changes without having to deploy the entire application.</li><li><strong>Database changes should be in a single transaction:</strong> Either the entire migration succeeds or it fails but not something in between.</li><li><strong>Idempotency: </strong>We can run the migration command as many times as we want but changes to the database will only be applied once.</li></ul><h3><strong>Tools that satisfy our database migration system requirements</strong></h3><p>There are some tools out there that satisfy all of the requirements. One that seems very popular, according to the number of <a href="https://flywaydb.org/blog/docker-1000000">docker images downloads</a>, is <a href="https://flywaydb.org/">Flyway</a>. I personally have successfully used <a href="https://github.com/sqitchers/sqitch">sqitch</a> for the last couple of years.</p><p>While this is not a comprehensive tutorial on how to use any of the tools, for the sake of completing the argument here an example of a typical sqitch workflow. Once we have <a href="https://github.com/sqitchers/sqitch/blob/master/lib/sqitchtutorial.pod">sqitch configured</a>, imagine our first migration is named initial_migration:</p><pre># This will create a new migration named “users_table” that depends on a previous migration named “initial_migration”</pre><pre>sqitch add users_table -r initial_migration -n “Create users table”</pre><p>The previous command will create 3 files, a file under the deploy folder, a file under the revert folder and one under the verify folder (we’ll ignore this last one).</p><p>Now we need to add a PostgreSQL deploy script:</p><pre>deploy/users_table.sql</pre><pre>BEGIN;</pre><pre># Needed to generate UUIDs<br>CREATE EXTENSION IF NOT EXISTS pgcrypto;</pre><pre>CREATE TABLE &quot;users&quot; (<br>    &quot;uuid&quot; uuid DEFAULT gen_random_uuid() NOT NULL PRIMARY KEY,<br>    &quot;created&quot; TIMESTAMP WITH TIME ZONE NOT NULL default NOW(),<br>    &quot;email&quot; TEXT NOT NULL,<br>    &quot;password&quot; TEXT NOT NULL,<br>    &quot;deleted&quot; BOOLEAN NOT NULL DEFAULT false    <br>);</pre><pre>CREATE UNIQUE INDEX user_email_for_non_deleted ON &quot;user&quot;(&quot;email&quot;)  WHERE (deleted is FALSE);</pre><pre>COMMIT;</pre><p>Now we need to add a PostgreSQL revert script:</p><pre>revert/users_table.sql</pre><pre>BEGIN;</pre><pre>DROP EXTENSION IF EXISTS pgcrypto;<br>DROP TABLE IF EXISTS &quot;users&quot;;</pre><pre>COMMIT;</pre><p>Then to deploy the changes to an already configured database we run:</p><pre># deploys pending migrations to production_db (already configured)</pre><pre>sqitch deploy -t production_db</pre><p>And if we want to revert the change we just need to:</p><pre>sqitch revert -t production_db --to-change initial_migration</pre><p>The last command will run all the revert scripts until and without including initial_migration. In our case, it will just run revert/users_table.sql.</p><h3><strong>Should we decouple database migrations from application deployments?</strong></h3><p>With ORMs when we deploy a database migration it usually occurs during an application deployment, giving a false illusion that both the database change and the code update happen at the same time.</p><p>Well, bad news, they happen sequentially, which means that there is a period of time in which the database has the new changes, but the application doesn’t have the new code.</p><p>The best case scenario, the one that we always have in mind, is this delay in time is just a couple of seconds.</p><p>In the worse case scenario, the database is updated, the application deployment fails for whatever reason, we don’t have the proper database rollback strategy and the new database has some breaking changes to the currently deployed application. Then our application remains broken until we rollback the database changes or we fix the deployed application.</p><p>It is better to isolate the deployment of database changes from the deployment of application changes to make it very explicit to everyone that <strong>database migrations and application deployments don’t happen at the same time.</strong> Then we will always remember to write non-breaking changes when creating migration scripts.</p><p>The 2 main benefits to decoupling database changes from application changes are:</p><ul><li>It’s explicit that both don’t happen at the same time, which makes every developer writing database migrations very aware of it.</li><li>By decoupling the application lifecycle from the database lifecycle, the database schema will probably be managed and modified by fewer and more database-savvy developers than if everything is coupled and managed by the same group of <a href="https://medium.com/system-is-asset-code-is-liability/the-mythical-full-stack-developer-f4414ca52830">full stack developers</a>.</li></ul><h3><strong>How to write non-breaking database migrations</strong></h3><blockquote>When in doubt, ask <a href="https://purelyfunctional.tv/programmer-profiles/rich-hickey/">Rich Hickey</a>.</blockquote><p>In his 2016 “<a href="https://www.youtube.com/watch?v=oyLBGkS5ICk">Spec-ulation keynote</a>” Rich addresses how to write non-breaking code in general. In particular, the implementation of non-breaking database migrations would be:</p><ul><li><strong>Accretion is good.</strong> Adding new tables, columns, … are non-breaking changes.</li><li><strong>Deletion is bad.</strong> Only remove tables, columns, … when no other part of the system is using it. Rich Hickey will say never to delete anything.</li><li><strong>Updates are bad and tricky.</strong> When updating a column name, table name, … treat it as multiple steps in which we add the new desired element (keeping the old and new one), we port every other part of the system to use the new one and then we remove the old one. Rich Hickey would say to just alias the old construct and keep both.</li></ul><h3>Building the system</h3><p>We’ve previously explained <a href="https://medium.com/system-is-asset-code-is-liability/dont-be-a-sucker-and-stop-using-orms-190add65add4">why ORMs are detrimental</a>. In this article, we have explored why and how to decouple the database migration system from the ORM.</p><p>By using an ORM for database migrations, and migrating the database/deploying application updates “simultaneously” we are making our system easier to manage in straightforward cases but more difficult to maintain in the long run, especially when something fails.</p><p>This difficulty comes from multiple types of changes (database and application updates) happening in what’s erroneously thought of at the same time.</p><p>By decoupling the database migration system from the ORM and the application lifecycle, we make very explicit that database migrations and code updates don’t happen at the same time. So it becomes very evident that we shouldn’t introduce database breaking changes, which in turn makes the overall system stronger.</p><p>Next, we’ll give some practical advice on <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-replacing-connection-handling-25466845ff9">how to handle the database connection</a> and <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-replacing-database-queries-3e8c4820d697">manage database queries</a> so we can finally break free for once and for all from the ORM.</p><h3>References</h3><ol><li><a href="https://www.youtube.com/watch?v=oyLBGkS5ICk">Spec-ulation (Rich Hickey)</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6e53d144cab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-the-system/breaking-free-from-the-orm-decoupling-database-migrations-e6e53d144cab">Breaking Free From the ORM: Decoupling Database Migrations</a> was originally published in <a href="https://medium.com/building-the-system">Building the system</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Free From the ORM: Why Move On?]]></title>
            <link>https://medium.com/building-the-system/dont-be-a-sucker-and-stop-using-orms-190add65add4?source=rss-2596e24c8ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/190add65add4</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[object-relational-mapping]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Omar Rayward]]></dc:creator>
            <pubDate>Sun, 05 Aug 2018 14:44:37 GMT</pubDate>
            <atom:updated>2018-10-01T13:31:29.369Z</atom:updated>
            <content:encoded><![CDATA[<h4>Time to escape object relational mapping</h4><blockquote>TL;DR, Reduce complexity in in your programs by avoiding the use of ORMs.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*6jABcIujmCnv8DKA4ffH4Q.png" /></figure><p>Object Relational Mapping or<strong> </strong><a href="https://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a> is one of those constructs that, as software developers, we would have benefited from if it simply never existed.</p><p>Three years ago, frustrated by the number of times I had to revisit <a href="https://docs.djangoproject.com/en/2.0/topics/db/">Django’s ORM documentation</a>, <a href="https://medium.com/u/bcc1be20ae27">Myles Byrne</a> suggested I read <a href="http://blogs.tedneward.com/post/the-vietnam-of-computer-science/">The Vietnam of Computer Science</a>. It was a refreshing experience that articulated my distaste for ORMs.</p><blockquote>The Vietnam of Computer Science is from 2006, and it is still very relevant today. Following the <a href="https://en.wikipedia.org/wiki/Lindy_effect">Lindy effect</a>, it will probably remain relevant ten years from now. If you have ever exploded in anger because of some unexpected consequence using an ORM, I would recommend setting some time aside over the next week to read it and understand the structural limitations of ORMs.</blockquote><h3><strong>Four Good Reasons to Escape ORMs</strong></h3><h4>1. ORMs GREATLY INCREASE INCIDENTAL COMPLEXITY (EASY IS NOT SIMPLE)</h4><p>ORMs are “easy” to use, but they come with a lot of incidental complexity that sooner or later will surface in our programs. In this case, <a href="https://www.infoq.com/presentations/Simple-Made-Easy">easy is not the same as simple.</a></p><p>Incidental complexity in <a href="https://github.com/matthiasn/talk-transcripts/blob/master/Hickey_Rich/SimpleMadeEasy.md">Rich Hickey’s words</a>:</p><blockquote>The output of the constructs that we create in our programs is a source of complexity. We’re going to call that incidental complexity. Incidental complexity wasn’t part of what the user asked us to do. We chose a tool. It had some inherent complexity in it. It’s incidental to the problem. I didn’t put the definition in here, but incidental is Latin for <strong>your fault</strong>.</blockquote><pre>email = User.find(id=1).email</pre><p>OK, that was easy. I just needed to get theUser object by id then retrieve its email.</p><p>Now, try answering these questions:</p><ul><li>Was a database connection open when executing that line of code or was it open at a previous time?</li><li>Are we using a connection from a database connection pool?</li><li>How much data did we retrieve from the database?</li><li>Do we need all the data retrieved from the database?</li><li>Is that line of code fetching data from the database or is it accessing an internal cache?</li><li>If there is a cache, when is it going to be refreshed?</li><li>Does that line of code automatically commit to the database?</li></ul><p>From reading that single line of code, I am unable to answer any of those questions.</p><p>Now, let’s try answering the previous questions with this code:</p><pre>conn = psycopg2.connect(&#39;postrges://...&#39;)<br>with conn.cursor() as cur:<br>    conn.execute(&#39;SELECT email FROM users WHERE id=1&#39;)<br>    email = conn.fetchall()<br>conn.commit()</pre><p>This snippet of code is more challenging to create because it requires understanding what we are doing. But, it is a lot simpler than the previous “one-liner”.</p><p>From the new code, we can answer all of the questions.</p><p>Here’s another example:</p><pre>team_names = User.find(id=1).teams.map(team =&gt; team.name)</pre><p>Try answering this question:</p><ul><li>How many database queries is that “one-liner” making?</li></ul><h4>2. ORMs ALWAYS BREAK THEIR IMPLICIT CONTRACT</h4><p>Each time we introduce a dependency, we concede to the following tacit agreement:</p><blockquote>Hey developer, if you use me as a third-party library, I’ll make your life easier:</blockquote><blockquote>- I’ll abstract a piece of knowledge you don’t need to build a better product faster.</blockquote><blockquote>- I’ll provide such good API and documentation that you will rarely (if ever) need to understand how I’m doing what I’m doing. Trust me, I have you covered.</blockquote><p>The implicit value proposition of an ORM is it will abstract anything related to data using a familiar Object Oriented Interface.</p><p>This is simply not true.</p><p>ORMs are <em>not</em> a substitute for databases. If and when we need to use the full capabilities of the underlying database, the ORM falls short, resulting in the need to write raw database queries.</p><p>When using an ORM, it’s not enough to know how to use a database feature. We also need to know what the best way to implement it is using its DSL (<a href="https://en.wikipedia.org/wiki/Domain-specific_language">Domain-specific Language</a>). The back and forth between the database DSL and the ORM’ DSL is useless overhead.</p><blockquote>When there is doubt, there is no doubt.</blockquote><blockquote>If you are currently using an ORM and can’t escape it; whenever debating whether to write raw SQL or learn the ORM’s DSL, then you’ve gone too far — always use raw SQL.</blockquote><h4>3. ORMs IMPLICITLY ASSIGN MORE VALUE TO CODE THAN DATA</h4><p>An ORM is a piece of software that purposefully hides the underlying database, while simultaneously aligning itself with an architecture that assigns more value to code than data.</p><p>By using an ORM, we silently scream, “The source of truth is the code — the database is just an artifact!”</p><p>This is wrong. Very wrong. Between code and data, data is the asset; code is the liability. Code is just a tool to expose data to different stakeholders. We should make architecture decisions aligned with this view of the world.</p><h4>4. ORMs COMBINE TOO MANY COMPETENCIES</h4><p>When we’re sold on an ORM, we are usually buying three constructs at once:</p><ul><li>Database migrations</li><li>Database connection handling with predefined or configurable connection pooling</li><li>Database read/write queries with a predefined or configurable commit logic</li></ul><p>We usually place these three constructs in the same location as the business logic (application code), which is especially painful to see for database migrations.</p><p>By placing migrations within the application code we bundle the database schema lifecycle with the application’s lifecycle. It’s noticeably worse if we want to create other applications on top of the same database (as we won’t be able to decouple the new application’s lifecycle from that holding the database migrations).</p><h3>Building the system</h3><p>Complexity in our code is a liability. As developers, we add a great degree of complexity to our code by using ORMs.</p><p><a href="https://www.artofmanliness.com/articles/via-negativa-adding-to-your-life-by-subtracting/"><em>Via negativa</em></a> (less is more)<em>: </em>By avoiding the use of ORMs and understanding what functionality we need to implement in our applications, we can build a robust foundation for our engineering team. It opens deeper level architecture discussions such as whether to favor objects versus data, leading to a stronger overall <strong>system</strong>.</p><p>In this first of a four-part series, we have explored why we need to escape the use of ORMs. In the next three parts, we will explore tools and provide practical advice on how to remove the ORM by <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-decoupling-database-migrations-e6e53d144cab">migrating the database with different tools</a>, <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-replacing-connection-handling-25466845ff9">handling database connections ourselves</a> and <a href="https://medium.com/system-is-asset-code-is-liability/breaking-free-from-the-orm-replacing-database-queries-3e8c4820d697">managing database queries</a>.</p><h3>References</h3><ol><li><a href="http://blogs.tedneward.com/post/the-vietnam-of-computer-science/">The Vietnam of Computer Science(Ted Neward)</a>.</li><li><a href="https://www.infoq.com/presentations/Simple-Made-Easy">Simple Made Easy (Rich Hickey)</a>.The <a href="https://github.com/matthiasn/talk-transcripts/blob/master/Hickey_Rich/SimpleMadeEasy.md">transcript</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=190add65add4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-the-system/dont-be-a-sucker-and-stop-using-orms-190add65add4">Breaking Free From the ORM: Why Move On?</a> was originally published in <a href="https://medium.com/building-the-system">Building the system</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The mythical Full Stack developer]]></title>
            <link>https://medium.com/building-the-system/the-mythical-full-stack-developer-f4414ca52830?source=rss-2596e24c8ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4414ca52830</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[hiring]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Omar Rayward]]></dc:creator>
            <pubDate>Sun, 29 Jul 2018 06:06:03 GMT</pubDate>
            <atom:updated>2018-09-30T02:59:15.870Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reasons to not hire Full Stack developers and to avoid presenting oneself as a such.</h4><blockquote>TL;DR, Avoid the “Full Stack idea”. As a company you’ll save money, as a developer you’ll save time.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oriakHdcfqsPgPSwC9IBNQ.jpeg" /><figcaption>A disaster waiting to happen</figcaption></figure><h3>Context</h3><p>The ideas expressed in this article refer to the development of software applications in a <a href="https://en.wikipedia.org/wiki/Multitier_architecture">3-tier architecture</a>:</p><ul><li>Presentation tier: Top level tier, responsible for the User Interface (client). Front-End developers usually implement it.</li><li>Logic tier: It controls the application logic. Back-End developers usually implement it.</li><li>Data tier: Persistency layer, anything related to storage and management of data. Historically managed by DBA (Database Administrators) but I feel, that due to the massive usage of <a href="https://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a>s the Data tier is frequently led by Back-End developers.</li></ul><p>A Full Stack developer is someone that could contribute to any of those three tiers at any given time. In this article when talking about Full Stack developers, I’m referring to the group of developers that have a general understanding, but not expertise in each of those three tiers.</p><p>There are Full Stack developers that are experts at every layer of the stack, they are rare to find, and are intentionally left out from this article.</p><h3>Myth</h3><p><em>Full Stack developers are a great asset. They can work in multiple if not all parts of the application. So depending on the business needs, these Full Stack developers can contribute to any part of the stack.</em></p><p>If one week the bulk of the work is in the client (Presentation tier); no problem, the Full Stack developer will deal with it.</p><p>If next week, the features to be developed demand more work in the data or logic tier; no problem, the same Full Stack developer will deal with them, providing the same level of proficiency.</p><blockquote>Life is wonderful. We are a super agile team able to adapt to the market every single week. We are the epitome of the Lean Startup movement.</blockquote><h3>Consequences</h3><p>Three to six weeks after those incredible “super agile” weeks, development of features starts slowing down. Features that used to take a sprint, now take more than double.</p><p>Every new product idea gets pushback by the engineering team because of some obscure technical reason, that usually involves a framework or database that was great just a couple of weeks back.</p><p>Moreover, motivation and confidence within the engineering team decreases.</p><blockquote>The honeymoon is over. It’s time to address these structural deficiencies at the next all-hands meeting.</blockquote><h3>The 5 Whys (Reality check)</h3><ul><li>Why does it take so long to develop new features?</li></ul><p>Because there are parts of the codebase that get in the way of developing them.</p><ul><li>Why did the codebase get into this state?</li></ul><p>Because there were some suboptimal software architecture decisions made in the past that lead to a convoluted implementation.</p><ul><li>Why did we make those suboptimal software architecture decisions?</li></ul><p>Because we don’t have architect level experience in that part of the stack. We just chose what seemed the right tool for the job, which was the easiest tool to use. We copy-pasted the “Quickstart” setup, and for any additional questions on how to effectively use the chosen tool, we went to Stack Overflow.</p><ul><li>Why don’t we have architect level experience in that part of the stack?</li></ul><p>Because we have a team of Full Stack developers. That makes us very agile, depending on the business needs, these Full Stack developers can contribute to any part of the stack.</p><ul><li>Why do we have a team of Full Stack developers and why haven’t we hired specific expertise for the different parts of our stack?</li></ul><p>Because at that time we didn’t know what to hire for. The only thing we knew is that we needed more developers on the team because we wanted to build x new more features. Instead of thinking in advance what specific developer expertise we needed, we decided to hire Full Stack developers, which seemed like a smart thing to do.</p><h3>Discussion</h3><p>I’m not sure what came first, companies looking for Full Stack developers or developers presenting themselves as Full Stack. I guess that the former did as a means to cut corners.</p><p>In my experience, software developers that present themselves as Full Stack are usually mid-level developers with two distinct profiles:</p><ul><li>Front End developers that have some experience with the business logic tier and the only exposure that they’ve had with the data tier is by working with ORMs.</li><li>Back End developers that know how to write a little bit of Javascript (+ <a href="https://jquery.com/">jQuery</a>) and have read a couple <a href="https://reactjs.org/">React</a> tutorials.</li></ul><p>The reason for software developers to present themselves as Full Stack is to increase their chances of getting hired.</p><p>Due to the favorable market conditions for senior developers, as mid-level developers gain expertise, they stop claiming they are Full Stack and start presenting themselves as experts on a specific part of the stack.</p><p>On the other hand, companies looking to hire Full Stack developers, don’t know what they are looking for. Either because the person responsible for hiring is not able to architect the workload coming ahead or because the workload is not even defined.</p><h3>Conclusion</h3><p>It’s understandable for both sides (developers and companies) to be seduced by the “Full Stack” concept, but it may have negative consequences in the mid-long term.</p><h4>For developers</h4><blockquote>Don’t waste your time.</blockquote><p>As a mid-level developer, you should look for the best environment to gain expertise at whatever layer of the stack you choose to specialize in.</p><p>It’s OK to use the “Full Stack” concept to increase your chances of being hired, but when that happens, make sure that the team has enough expertise at each layer of the stack. If not, sooner than you imagine you’ll be in a room full of overly motivated mid-level developers discussing architecture solutions that none of you have ever implemented. You’ll be wasting much precious time without realizing it.</p><h4>For companies</h4><blockquote>Don’t waste your money.</blockquote><p>Full Stack developers look very appealing on paper, but <em>the devil is in the details</em>. Be aware that these developers may inadvertently make suboptimal architecture decisions that will increase the technical debt. The company will have to deal with it in the immediate future.</p><h3>Addendum</h3><h4>Is there a time to hire Full Stack developers?</h4><p>Yes, whenever there is going to be a team of one developer managing the entire application.</p><p>Beyond that, the company would be better off by hiring experts or at least developers just focused on one part of the stack.</p><h4>Is this important for companies?</h4><p>Hiring specialized engineers early on is only relevant for companies that being operationally efficient is one of their top priorities.</p><p>Most of the companies around the world know that operational efficiency is critical for their survival. However, in the Bay Area, the most crucial priority seems to be raising a massive amount of money.</p><p>If you work on one of those super well-funded companies, then your company has much, much more time to figure this out and by hiring experts, someone will probably come in and solve the issue.</p><p>If you work or have a small/medium revenue grown company, then operational efficiency and focusing on hiring experts in each layer of the stack as soon as possible proves much more cost-effective on the mid-long run.</p><h3>Building the system</h3><p>Building the right engineering team is vital to the success of a software-based company.</p><p>In this case, <strong>building the system</strong><em> </em>means understanding the technical expertise required by your company and hiring accordingly. There are 10x developers out there, but they’re not the Full Stack mid-level ones.</p><h3>Inspiration</h3><ol><li><em>All that glitters is not gold. </em><a href="https://www.amazon.com/Mythical-Man-Month-Software-Engineering-Anniversary/dp/0201835959/ref=sr_1_1">The mythical man-month</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4414ca52830" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-the-system/the-mythical-full-stack-developer-f4414ca52830">The mythical Full Stack developer</a> was originally published in <a href="https://medium.com/building-the-system">Building the system</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better performance by optimizing Gunicorn config]]></title>
            <link>https://medium.com/building-the-system/gunicorn-3-means-of-concurrency-efbb547674b7?source=rss-2596e24c8ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/efbb547674b7</guid>
            <category><![CDATA[systems-engineering]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Omar Rayward]]></dc:creator>
            <pubDate>Mon, 16 Jul 2018 09:49:32 GMT</pubDate>
            <atom:updated>2018-09-29T22:39:53.964Z</atom:updated>
            <content:encoded><![CDATA[<h4>Practical advice on how to configure Gunicorn.</h4><blockquote><em>TL;DR, For CPU bounded apps increase workers and/or cores. For I/O bounded apps use “pseudo-threads”.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39XEUZgpoUUzahu7giTlAw.png" /></figure><p><a href="http://gunicorn.org/">Gunicorn</a> is a Python WSGI HTTP Server that usually lives between a <a href="https://en.wikipedia.org/wiki/Reverse_proxy">reverse proxy</a> (e.g., <a href="https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/">Nginx</a>) or <a href="https://f5.com/glossary/load-balancer">load balancer</a> (e.g., <a href="https://aws.amazon.com/elasticloadbalancing/">AWS ELB</a>) and a web application such as Django or Flask.</p><h3><a href="http://docs.gunicorn.org/en/latest/design.html">Gunicorn architecture</a></h3><p>Gunicorn implements a UNIX pre-fork web server.</p><p>Great, what does that mean?</p><ul><li>Gunicorn starts a single master process that gets forked, and the resulting child processes are the workers.</li><li>The role of the master process is to make sure that the number of workers is the same as the ones defined in the settings. So if any of the workers die, the master process starts another one, by forking itself again.</li><li>The role of the workers is to handle HTTP requests.</li><li>The <em>pre</em> in <em>pre-forked</em> means that the master process creates the workers before handling any HTTP request.</li><li>The OS kernel handles load balancing between worker processes.</li></ul><p>To improve performance when using Gunicorn we have to keep in mind 3 means of concurrency.</p><h4>1st means of concurrency (workers, aka UNIX processes)</h4><p>Each of the workers is a UNIX process that loads the Python application. There is no shared memory between the workers.</p><p>The suggested <a href="http://docs.gunicorn.org/en/latest/design.html#how-many-workers">number of </a><a href="http://docs.gunicorn.org/en/latest/design.html#how-many-workers">workers</a> is (2*CPU)+1.</p><p>For a dual-core (2 CPU) machine, 5 is the suggested workers value.</p><pre>gunicorn --workers=5 main:app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbgEx24X6sZ204k5HOs3WA.png" /><figcaption>Gunicorn with default worker class (sync). Note the 4th line in the image: “Using worker: sync”.</figcaption></figure><h4>2nd means of concurrency (threads)</h4><p>Gunicorn also allows for each of the workers to have multiple threads. In this case, the Python application is loaded once per worker, and each of the threads spawned by the same worker shares the same memory space.</p><p>To use threads with Gunicorn, we use the threads setting. Every time that we use threads, the worker class is set to gthread:</p><pre>gunicorn --workers=5 --threads=2 main:app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkpM7HoS_4PClLOVH9lCew.png" /><figcaption>Gunicorn with threads setting, which uses the gthread worker class. Note the 4th line in the image: “Using worker: threads”.</figcaption></figure><p>The previous command is the same as:</p><pre>gunicorn --workers=5 --threads=2 --worker-class=gthread main:app</pre><p>The maximum concurrent requests areworkers * threads 10 in our case.</p><p>The suggested maximum concurrent requests when using workers and threads is still(2*CPU)+1.</p><p>So if we are using a quad-core (4 CPU) machine and we want to use a mix of workers and threads, we could use 3 workers and 3 threads, to get 9 maximum concurrent requests.</p><pre>gunicorn --workers=3 --threads=3 main:app</pre><h4>3rd means of concurrency (“pseudo-threads” )</h4><p>There are some Python libraries such as <a href="http://www.gevent.org/">gevent</a> and <a href="https://docs.python.org/3/library/asyncio.html">Asyncio</a> that enable concurrency in Python by using “pseudo-threads” implemented with <a href="https://en.wikipedia.org/wiki/Coroutine">coroutines</a>.</p><p>Gunicorn allows for the usage of these asynchronous Python libraries by setting their corresponding worker class.</p><p>Here the settings that would work for a single core machine that we want to run using gevent:</p><pre>gunicorn --worker-class=gevent --worker-connections=1000 --workers=3 main:app</pre><blockquote>worker-connections is a specific setting for the gevent worker class.</blockquote><p>(2*CPU)+1 is still the suggested workers since we only have 1 core, we’ll be using 3 workers.</p><p>In this case, the maximum number of concurrent requests is 3000 (3 workers * 1000 connections per worker)</p><h3>Concurrency vs. Parallelism</h3><ul><li>Concurrency is when 2 or more tasks are being performed at the same time, which might mean that only 1 of them is being worked on while the other ones are paused.</li><li>Parallelism is when 2 or more tasks are executing at the same time.</li></ul><p>In Python, threads and pseudo-threads are a means of concurrency, but not parallelism; while workers are a means of both concurrency and parallelism.</p><p>That’s all good theory, but what should I use in my program?</p><h3>Practical use cases</h3><p>By tuning Gunicorn settings we want to optimize the application performance.</p><ol><li>If the application is <a href="https://en.wikipedia.org/wiki/I/O_bound">I/O bounded</a>, the best performance usually comes from using “pseudo-threads” (gevent or asyncio). As we have seen, Gunicorn supports this programming paradigm by setting the appropriate <strong>worker class</strong> and adjusting the value of <strong>workers</strong>to (2*CPU)+1.</li><li>If the application is <a href="https://en.wikipedia.org/wiki/CPU-bound">CPU bounded</a>, it doesn’t matter how many concurrent requests are handled by the application. The only thing that matters is the number of parallel requests. Due to <a href="https://wiki.python.org/moin/GlobalInterpreterLock">Python’s GIL</a>, threads and “pseudo-threads” cannot run in parallel. The only way to achieve parallelism is to increase <strong>workers </strong>to the suggested (2*CPU)+1, understanding that the maximum number of parallel requests is the number of cores.</li><li>If there is a concern about the application <a href="https://en.wikipedia.org/wiki/Memory_footprint">memory footprint</a>, using <strong>threads </strong>and its corresponding <strong>gthread worker class</strong> in favor of workers yields better performance because the application is loaded once per worker and every thread running on the worker shares some memory, this comes to the expense of some additional CPU consumption.</li><li>If you don’t know you are doing, start with the simplest configuration, which is only setting <strong>workers</strong> to (2*CPU)+1 and don’t worry about threads. From that point, it’s all trial and error with benchmarking. If the bottleneck is memory, start introducing threads. If the bottleneck is I/O, consider a different python programming paradigm. If the bottleneck is CPU, consider using more cores and adjusting the <strong>workers</strong> value.</li></ol><h3>Building the system</h3><p>We, software developers commonly think that every performance bottleneck can be fixed by optimizing the application code, and this is not always true.</p><p>There are times in which tuning the settings of the HTTP server, using more resources or re-architecting the application to use a different programming paradigm are the solutions that we need to improve the overall application performance.</p><p>In this case, <strong>building the system </strong>means understanding the types of computing resources (processes, threads and “pseudo-threads”) that we have available to deploy a performant application.</p><p>By understanding, architecting and implementing the right technical solution with the right resources we avoid falling into the trap of trying to improve performance by optimizing application code.</p><h3>References</h3><ol><li><em>Gunicorn is ported from Ruby’s </em><a href="https://bogomips.org/unicorn/"><em>Unicorn</em></a><em> project. Its </em><a href="https://bogomips.org/unicorn/DESIGN.html"><em>design outline</em></a><em> helped on clarifying some of the most fundamental concepts. </em><a href="http://docs.gunicorn.org/en/latest/design.html"><em>Gunicorn architecture</em></a><em> cemented some of those concepts.</em></li><li><a href="https://tomayko.com/blog/2009/unicorn-is-unix"><em>Opinionated blog post</em></a><em> about how Unicorn deferring some of the most critical features to Unix is good.</em></li><li><em>Stack Overflow answer about the pre-fork web server model.</em></li><li><a href="https://github.com/benoitc/gunicorn/issues/1045"><em>Some</em></a><em> </em><a href="https://stackoverflow.com/questions/38425620/gunicorn-workers-and-threads"><em>more</em></a><em> </em><a href="http://docs.gunicorn.org/en/stable/settings.html"><em>references</em></a><em> to understand how to fine tune Gunicorn.</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efbb547674b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-the-system/gunicorn-3-means-of-concurrency-efbb547674b7">Better performance by optimizing Gunicorn config</a> was originally published in <a href="https://medium.com/building-the-system">Building the system</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to store dates and times in PostgreSQL?]]></title>
            <link>https://medium.com/building-the-system/how-to-store-dates-and-times-in-postgresql-269bda8d6403?source=rss-2596e24c8ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/269bda8d6403</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Omar Rayward]]></dc:creator>
            <pubDate>Mon, 09 Jul 2018 07:29:48 GMT</pubDate>
            <atom:updated>2018-09-29T22:38:51.761Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to store dates and times in PostgreSQL</h3><h4>The ultimate guide to understanding timestamp data types.</h4><blockquote>TL;DR, Use PostgreSQL’s “timestamp with time zone” (“timestamptz”).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imep5Aq2pO1SBCto1R52Fw.png" /></figure><p>When developing software applications, we usually have users across multiple geographic areas in different timezones, which means that to accurately represent a date and time in a single data type(timestamp) it needs to be timezone aware.</p><p>In this article, we are going to explore how to store timestamps in PostgreSQL and how to make our life more comfortable, as software developers, by deferring the “hard work” to the PostgreSQL runtime.</p><h3>Constraints</h3><ul><li>PostgreSQL has a timezone configuration parameter that can be modified. Usually, it’s only set once, ‘UTC’ in most cases.</li></ul><pre>-- Check timezone in psql<br>SHOW time zone;<br>+---------------+<br>| TimeZone      |<br>+---------------+<br>| UTC           |<br>+---------------+</pre><pre>-- Change timezone value<br>SET TIME ZONE &#39;Europe/Rome&#39;;</pre><pre>-- Check new timezone value<br>SHOW time zone;<br>+---------------+<br>| TimeZone      |<br>+---------------+<br>| &#39;Europe/Rome&#39; |<br>+---------------+</pre><ul><li>By timezone aware timestamps we mean timestamps with an offset, e.g., <em>2000–01–01 00:00:00 </em><strong><em>+0700</em></strong></li><li>In most cases, the client attempts to store timezone aware timestamps.</li><li>In the rare case in which a client attempts to store a timezone unaware timestamp, we’ll assume the PostgreSQL timezone configuration value as its timezone.</li><li>Every time that we read a timestamp value, it should be timezone aware.</li></ul><h3><strong>PostgreSQL date and times data types</strong></h3><p>PostgreSQL has <a href="https://www.postgresql.org/docs/current/static/datatype-datetime.html">six different data types</a> to represent date and times from which only two store a date and a time in a single data type:</p><ul><li>“timestamp without time zone” (“timestamp”).</li><li>“timestamp with time zone” (“timestamptz”),</li></ul><p>From the documentation, it looks like both data types use 8 bytes of storage size, which doesn’t seem right because “timestamptz”<em> should</em> be storing more information that “timestamp”<em>. </em>Let’s make sure that the docs are right:</p><pre>SELECT <br>pg_column_size(&#39;2000-01-01 00:00:00 +00:00&#39;::timestamp) as &quot;timestamp byte size&quot;,<br>pg_column_size(&#39;2000-01-01 00:00:00 +00:00&#39;::timestamptz) as &quot;timestamptz byte size&quot;;<br>+--------------------+-----------------------+<br>|timestamp byte size | timestamptz byte size |<br>+--------------------+-----------------------+<br>|                  8 |                     8 |<br>+--------------------+-----------------------+</pre><p>What?</p><p>Both data types have 8 bytes. PostgreSQL is storing the same quantity of data for both data types, which means that “timestamptz” is not saving any additional timezone information.</p><p>Weird, how does it work?</p><h3>timestamp vs. timestamptz</h3><p>These 2 PostgreSQL data types store date and time in a single field, the difference is that “timestamptz” converts the value to UTC and “timestamp” doesn’t.</p><p>Let’s see an example:</p><pre>SET TIME ZONE &#39;UTC&#39;;</pre><pre>SELECT<br>&#39;2000-01-01 00:00:00 +05:00&#39;::timestamp as &quot;Timestamp without time zone&quot;,<br>&#39;2000-01-01 00:00:00 +05:00&#39;::timestamptz as &quot;Timestamp with time zone&quot;;</pre><pre>+---------------------------+------------------------+<br>|Timestamp without time zone|Timestamp with time zone|<br>+---------------------------+------------------------+<br>| 2000-01-01 00:00:00       |1999-12-31 19:00:00+00  |<br>+---------------------------+------------------------+</pre><p>From the previous example:</p><ul><li>The “timestamp” data type ignores the offset (‘+05:00’) from the original value.</li><li>The “timestamptz” data type takes into account the offset (‘+05:00’) from the original value.</li></ul><h3>Better PostgreSQL timestamp data type naming</h3><p>As we’ve seen, both datatypes store the same information, none related to timezone. “timestamptz” takes into account the offset, while “timestamp” ignores it. Here, better naming:</p><ul><li>“timestamp without time zone” (“timestamp”) means “<strong>timestamp offset unaware</strong>”.</li><li>“timestamp with time zone” (“timestamptz”) means “<strong>timestamp offset aware</strong>”.</li></ul><h3>Business use case</h3><p>Imagine we are developing an app that provides a chat interface to its users. Users can send messages, and we want to be able to show the messages’ timestamp to each user taking into account their geographical location (timezone).</p><p>For example, a user in UTC visualizes a message with timestamp “2000–01–01 <strong>0</strong>0:00:00”, and a different user in Rome (UTC -1) visualizes the same message with timestamp “2000–01–01 0<strong>1</strong>:00:00”.</p><p>Let’s explore the work to be done when choosing either “timestamp” or “timestamptz”:</p><h4>1. Using timestamp without time zone (timestamp)</h4><p>If we use “timestamp” as the data type to store the message’s date and time:</p><ul><li>The application layer needs to convert all timestamps to a predetermined timezone, which we’ll call “global timezone” (usually UTC) before writing it to the database.</li><li>We need to set the PostgreSQL timezone configuration value to be the same as the “global timezone” in the application; hence both the database and the application need to be in sync.</li><li>When reading from the database, if we want to convert the stored timestamp to the client’s timezone at the <strong>database layer</strong> we need to cast the value from “timestamp” to “timestamptz” and then convert it to the client’s timezone, e.g.:</li></ul><pre>SELECT (&#39;2000-01-01 00:00:00 +00:00&#39;::timestamp)<strong>::timestamptz at time zone &#39;Europe/Rome&#39;</strong> as &quot;Rome&#39;s timestamp&quot;;</pre><pre>+----------------------+<br>|  Rome&#39;s timestamp    |<br>+----------------------+<br>| 2000-01-01 01:00:00  |<br>+----------------------+</pre><ul><li>When reading from the database, if we want to convert the stored timestamp to the client’s timezone at the <strong>application layer</strong>, we’ll gather the value from the database (timezone unaware), treat it as timezone aware using the “base timezone” and convert it to the client’s timezone.</li></ul><h4>2. Using timestamp with time zone (timestamptz)</h4><p>If we use “timestamptz” as the data type to store the message’s date and time:</p><ul><li>When writing to the database, we’ll let PostgreSQL convert the timestamps to UTC (done automatically by setting the data type to be “timestamptz”).</li><li>We can set the PostgreSQL timezone configuration value to whatever value we want (<em>I always set it to UTC</em>). This timezone value will only be relevant in the minority of cases where the client writes a timezone unaware timestamp, in which case the PostgreSQL runtime assigns its timezone configuration value to the timestamp, making it timezone aware.</li><li>To convert the stored timestamp to the client’s timezone at the <strong>database layer</strong> we only need to convert it to the client’s timezone, e.g.:</li></ul><pre>SELECT &#39;2000-01-01 00:00:00 +00:00&#39;::timestamptz <strong>at time zone &#39;Europe/Rome&#39;</strong> as &quot;Rome&#39;s timestamp&quot;;</pre><pre>+----------------------+<br>|  Rome&#39;s timestamp    |<br>+----------------------+<br>| 2000-01-01 01:00:00  |<br>+----------------------+</pre><ul><li>To convert the stored timestamp to the client’s timezone at the <strong>application layer</strong>, we’ll gather the value from the database (timezone aware) and convert it to the client’s timezone.</li></ul><h3>Building the system</h3><p>In this case using “timestamptz” is a better approach than using “timestamp”, and honestly, I yet have to discover a use case in which using “timestamp” is superior to using “timestamptz”.</p><p>By using “timestamptz” instead of “timestamp”, we simplify the system:</p><ul><li>The application layer writing to the database is simpler because we don’t need to convert every timestamp to a previously determined timezone.</li><li>We don’t need to synchronize the timezone used by PostgreSQL and the timezone used by the application layer (what we’ve previously called “global timezone”).</li><li>When reading from the database and converting to the user’s timezone at the database layer, the data transformation has fewer steps.</li><li>When reading from the database and converting to the user’s timezone at the application layer, we don’t need to treat a timezone unaware timestamp as a timezone aware one.</li></ul><p>The database, like any other “piece” of the system, doesn’t live in isolation. It always needs an application layer reading from and writing to it.</p><p>This application layer enables enough flexibility to implement whatever logic we need. However, this flexibility comes with the inconvenient of having to maintain every line of code that we write.</p><p>In this case, <strong>building the system</strong><em> </em>means using the right PostgreSQL data type and letting its runtime do the “hard work” of storing every timestamp at UTC.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=269bda8d6403" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-the-system/how-to-store-dates-and-times-in-postgresql-269bda8d6403">How to store dates and times in PostgreSQL?</a> was originally published in <a href="https://medium.com/building-the-system">Building the system</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The system is the asset, code a liability]]></title>
            <link>https://medium.com/building-the-system/1970-01-01t00-00-00-00-00-8813a0ac62e5?source=rss-2596e24c8ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8813a0ac62e5</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[systems-architecture]]></category>
            <dc:creator><![CDATA[Omar Rayward]]></dc:creator>
            <pubDate>Mon, 02 Jul 2018 14:15:59 GMT</pubDate>
            <atom:updated>2018-09-29T22:37:57.250Z</atom:updated>
            <content:encoded><![CDATA[<h4>On the matter of software development.</h4><blockquote>When developing software focus on creating the simplest possible system instead of shoe-horning every solution into your language/framework of preference.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPap9PyLWZp8Fk4vRW-qZA.png" /></figure><p>Much has been written about the craftsmanship of writing code. Most of it is around how to solve a particular issue in a specific program, language or framework.</p><p>The central theme of these essays is that while understanding the programs, languages, and frameworks is necessary, it is much more important to know how everything fits in the overall system.</p><p>At the end of the day what matters is that the systems we create can serve our business needs, regardless of the programs, languages or frameworks that we use. By focusing on building the system, we’ll be able to develop faster and cheaper which will eventually lead to more business success and what’s more important: more fun and fewer late nights.</p><p>Close to the concept of building the system, growing the asset, it’s also worth exploring the idea of writing less code, removing liability. <a href="https://www.artofmanliness.com/articles/via-negativa-adding-to-your-life-by-subtracting/"><em>Via Negativa</em></a> applied to software development.</p><h4>Building the system: a “trivial” example</h4><p>By setting the right data type for a specific field at the database level, we will avoid the need to write application level logic to understand whether we could treat a value as its real data type or not.</p><p>A system is composed of hundreds or thousands of these atomic units of logic that if not dealt with the simplest approach, it will make the overall system more complex and challenging to maintain.</p><h3>The system is the asset</h3><p>Software applications always contain multiple programs that depend and interact with each other. On top of that we, humans, come with our inconsistent actions continually operating, maintaining and updating those applications.</p><p>The system is an ambiguous term that can be applied to a single application, a group of applications, a team, a company, <em>… </em>In this publication when talking about “the system,” we’ll be referring to humans, software and their interactions (workflows) involved in the lifespan of software applications.</p><p>The underlying assumption when talking about “the system” is that it has more value than the sum of its parts.</p><h3>Code is a liability</h3><p>Code is expensive to create and much more costly to maintain. The crux of the matter is that the people creating software move on more frequently than the code base does.</p><p>Moving on is not only changing companies, teams or projects but also `using a different set of tools or mental paradigms to solve the same old problems. When moving on, the previously created system suddenly gets much more expensive to maintain.</p><p>For the tangible, but especially for the intangible costs of code, we need to write and maintain as little code as possible for our business to succeed.</p><h3>Publication objectives</h3><ol><li><strong>Improve our knowledge</strong> of software development and architecture. By exposing our understandings on how to <strong>build the system</strong>, we wish to uncover many flaws in our reasonings and learn from them.</li><li><strong>Share knowledge</strong> by providing practical advice on how to solve some of the challenges that we all face when developing applications. Some, if not most of the solutions in software development are not technically challenging. When facing a technical problem, once exposed to the right solution, tool, or mental model, the unsolvable now seems manageable. Hopefully, these essays will help with this process.</li></ol><p>Not sure where this will lead, we’ll let the journey decide its destination.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8813a0ac62e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-the-system/1970-01-01t00-00-00-00-00-8813a0ac62e5">The system is the asset, code a liability</a> was originally published in <a href="https://medium.com/building-the-system">Building the system</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>