<?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 João Salgado on Medium]]></title>
        <description><![CDATA[Stories by João Salgado on Medium]]></description>
        <link>https://medium.com/@joao-slgd?source=rss-a7cd74ff6837------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8S-B1ime9n9v7q6AlvHPlg.jpeg</url>
            <title>Stories by João Salgado on Medium</title>
            <link>https://medium.com/@joao-slgd?source=rss-a7cd74ff6837------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:19:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joao-slgd/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[Partitioning your PostgreSQL table]]></title>
            <link>https://medium.com/@joao-slgd/partitioning-your-postgresql-table-d56c678d3276?source=rss-a7cd74ff6837------2</link>
            <guid isPermaLink="false">https://medium.com/p/d56c678d3276</guid>
            <category><![CDATA[partitioning]]></category>
            <category><![CDATA[partition]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[João Salgado]]></dc:creator>
            <pubDate>Mon, 06 May 2024 22:04:58 GMT</pubDate>
            <atom:updated>2024-06-03T23:05:22.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DAVPO-_dg_t9ZvQx" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=medium&amp;utm_medium=referral">Campaign Creators</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Context and Problem</h4><p>I recently had to deal with a PostgreSQL table with a very large number of rows in a heavily used database (read and write). The database was starting to have some performance issues and the number of rows was growing fast (+200,000 rows per day). The table reached more than 100 million rows.</p><p>It was similar to a notification system, where we store notifications sent to our customers, and a feature where the customer could view the data and filter by any field. It is important to say that it was not necessary to maintain a very long data history, as the old data was not useful for our client, 2 years of data were enough.</p><p>We had two options of consolidated databases in our company, PostgreSQL and Cassandra. Since Cassandra couldn’t handle pagination, filter and joins, we started looking at Postgres features before going to a third option.</p><p>It was then that I discovered postgres table partitioning and I’m going to show you how it perfectly solved our problem.</p><h4>Partitioning x Sharding</h4><p>Basically on <strong>partitioning,</strong> you have parent table in the same server that you can send queries to, but the data actually lives in many smaller child tables. PostgreSQL supports three main types of partitioning: <strong>range, list, and hash partitioning</strong>. Each type of partitioning is useful in different scenarios.</p><p><strong>Range partitioning </strong>is used to divide a table into partitions based on a range of values. For example, you can partition a table of sales data by date, with each partition containing data for a specific day, week, month or quarter.</p><p><strong>List partitioning </strong>is used to divide a table into partitions based on a list of values. For example, you can partition a table of customers by country, with each partition containing data for a specific country.</p><p><strong>Hash partitioning </strong>is used to divide a table into partitions based on a hash value. This type of partitioning is useful when you want to evenly distribute data across partitions, but don’t have a specific value to partition on.</p><p>Considering the <strong>range partitioning</strong>, you end up with something that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*rnWxC56jsJyu1q7ddEQfkw.png" /></figure><p><strong>Sharding </strong>have similar concetps but a significant difference:</p><blockquote>Sharding is a method for distributing a single dataset across multiple databases, which can then be stored on multiple machines. This allows for larger datasets to be split into smaller chunks and stored in multiple data nodes, increasing the total storage capacity of the system. <a href="https://www.mongodb.com/resources/products/capabilities/database-sharding-explained">https://www.mongodb.com/resources/products/capabilities/database-sharding-explained</a></blockquote><p>You can use the same stretegies of sharding (range, list, hash) with the addition of more 2: <strong>entity-relationship, geography</strong>.</p><p><strong>Entity relationship</strong> sharding keeps related data together on a single physical shard. For instance, consider the case of a shopping database with users and payment methods. Each user has a set of payment methods that is tied tightly with that user. As such, keeping related data together on the same shard can reduce the need for broadcast operations, increasing performance.</p><p><strong>Geography </strong>sharding, also keeps related data together on a single shard, but in this case, the data is related by geography. This is essentially ranged sharding where the shard key contains geographic information and the shards themselves are geo-located. For example, consider a dataset where each record contains a “country” field. In this case, we can both increase overall performance and decrease system latency by creating a shard for each country or region, and storing the appropriate data on that shard.</p><p>Considering the <strong>sharding</strong>, you end up with something that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*8zQZLnyW33y4u2ABrzJxJA.png" /></figure><p>PostgreSQL does not have a great support for sharding yet, but you can find some solutions in the market, as <a href="https://www.citusdata.com/">citusdata</a>.</p><h4>Trade off the solution</h4><p>Partitioning and sharding are great for scaling your read and write, but it’s not a silver bullet. You should consider whether the solution fits your use case and whether you can handle the drawbacks.</p><p><strong>Advantages of Partitioning</strong></p><ul><li>Performance Improvement: Partitioning can enhance query performance by allowing the database to process smaller chunks of data at a time. This is particularly beneficial for large tables where performance may degrade due to the volume of data.</li><li>Parallelism: PostgreSQL can leverage partitioning for parallel query execution, which can further enhance performance by utilizing multiple CPU cores for processing.</li><li>Index Efficiency: Partitioning can lead to more efficient indexing, as you can create indexes on individual partitions or sub-partitions, reducing the size of each index and improving query performance.</li><li>Ease of Maintenance: Partitioning can make certain maintenance tasks, such as data purging or archiving, easier to perform. You can drop or archive entire partitions without affecting other parts of the table.</li></ul><p><strong>Disadvantages of Partitioning</strong></p><ul><li>Complexity: Partitioning adds complexity to database design, implementation, and maintenance. It requires careful planning and ongoing management to ensure optimal performance and data integrity.</li><li>Query Optimization Challenges: While partitioning can improve query performance, it can also introduce optimization challenges, especially when queries involve multiple partitions or complex partitioning criteria.</li><li>Increased Storage Overhead: Depending on the partitioning strategy and data distribution, partitioned tables may have increased storage overhead compared to non-partitioned tables. This is due to metadata and additional structures associated with partitions.</li><li>Limited Use Cases: Partitioning is not suitable for every database scenario. It is most beneficial for large tables with a clear partitioning key, such as time-based data or range-based data. For smaller tables or tables with unpredictable access patterns, partitioning may not provide significant benefits.</li></ul><p><strong>Advantages of Sharding</strong></p><ul><li>Scalability: Sharding allows horizontal scaling by distributing data across multiple shards. This can significantly improve the system’s scalability, enabling it to handle large volumes of data and high transaction rates.</li><li>Performance: Sharding can lead to improved performance by reducing the load on individual database nodes. Queries and transactions can be distributed across multiple shards, allowing for parallel processing and faster response times.</li><li>High Availability: Sharding can enhance fault tolerance and availability. If one shard or database node fails, the system can continue to operate using other shards, minimizing downtime and ensuring data availability.</li><li>Geographic Distribution: Sharding supports geographic distribution of data, which can be beneficial for applications that require data locality or compliance with regional data regulations.</li><li>Isolation: Sharding provides isolation between different sets of data, allowing for better resource utilization and performance optimization for specific data segments.</li></ul><p><strong>Disadvantages of Sharding</strong></p><ul><li>Complexity: Sharding introduces complexity in database design, implementation, and management. It requires careful planning of shard keys, data distribution strategies, and coordination among shards.</li><li>Data Consistency: Maintaining data consistency across shards can be challenging, especially in distributed transactions or when dealing with inter-shard dependencies. Implementing mechanisms like distributed transactions or eventual consistency adds complexity and overhead.</li><li>Query Complexity: Sharding can make certain types of queries more complex, especially those that require data aggregation or join operations across multiple shards. Query routing and coordination mechanisms are needed to handle such queries efficiently.</li><li>Cost: While sharding can improve scalability and performance, it may also increase infrastructure and operational costs. Managing multiple database nodes, ensuring data consistency, and implementing monitoring and management tools for sharded environments incur additional expenses.</li></ul><h4>Let’s implement</h4><p>Okay, enough context, let’s get to the point.</p><p>To better use the PostgreSQL partitioning features, I recommend use at least the version 14, I didn’t test in previous versions. Futhermore we will use 2 postgres extensions: <a href="https://github.com/citusdata/pg_cron">pg_cron</a>, <a href="https://github.com/pgpartman/pg_partman">pg_partman</a>.</p><p><strong>pg_partman: </strong>Responsible for maintaining the configurations and scripts that will automatically maintain our partitioning structure.</p><p><strong>pg_cron:</strong> Responsible for executing our partitioning maintenance scripts automatically.</p><p>So first we create these extensions in the database and two schemas, they will keep the metadata and our retention data separate from the main schema.</p><pre>create schema if not exists partman;<br>create schema if not exists retention;<br><br>create extension if not exists pg_partman with schema partman;<br>create extension if not exists pg_cron;</pre><p>Then we can create our partitioned table and an index:</p><pre>create table if not exists notifications<br>(<br>  id bigserial not null,<br>  created_at timestamp not null default now(),<br><br>  constraint pk_trigger_events primary key (id, created_at),<br>) partition by RANGE(created_at);<br><br><br>create index notifications_created_at_brin_idx on notifications using BRIN (created_at) with (pages_per_range = 32);</pre><p>Note that we have already flagged that our table is a partitioned table. Additionally, we create an index that will improve the speed of our query within each partition.</p><p>Now we will define how our partitioned table will work:</p><pre>select partman.create_parent(&#39;public.notifications&#39;, &#39;created_at&#39;, &#39;native&#39;, &#39;daily&#39;, p_start_partition := &#39;2024-01-01&#39;);<br><br>update partman.part_config<br>set infinite_time_partitions = true,<br>    retention = &#39;24 months&#39;, -- 2 years<br>    retention_keep_table=true,<br>    retention_schema=&#39;retention&#39;<br>where parent_table = &#39;public.notifications&#39;;<br><br></pre><p>The first command will create an input configuration for our partitioned table</p><ul><li><strong>Table name:</strong> public.notifications</li><li><strong>Partition key:</strong> created_at</li><li><strong>Partition strategy:</strong> native</li><li><strong>Partition range:</strong> daily</li><li><strong>Partition Start Date:</strong> 2024–01–01</li></ul><p>The second one will add more configurations:</p><ul><li><strong>Infinity number of partitions:</strong> true</li><li><strong>Retention in public schema:</strong> 24 months</li><li><strong>Keep table after retention period in public schema:</strong> true</li><li><strong>Retention schema after retention period:</strong> retention</li></ul><p>And finally we will configure our pg_cron to run our maintenance script every hour. This script will ensure that our settings are being applied correctly to our table.</p><pre>select cron.schedule(&#39;@hourly&#39;, $$CALL partman.run_maintenance_proc()$$);</pre><p>With this, our partitioned table is in automatic mode, a new partition will be created automatically, the data will expire after 24 months and will be stored in the retention scheme.</p><h4>Using partitioned table</h4><p>There’s no secret, you can access the parent table or the children. I recommend using only the parent table, because the partitioning mechanism will forward your query to the correct child table.</p><pre>select * <br>from notifications<br>where created_at &gt; &#39;2024-01-01T12:00:00&#39; </pre><p>Thanks for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*hNGciObPIzI01IzYcBdKZQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d56c678d3276" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with Geometric Data in Spring Boot 3 + Kotlin + PostgreSQL]]></title>
            <link>https://medium.com/@joao-slgd/dealing-with-geometric-data-in-spring-boot-3-kotlin-postgresql-1e90df24141c?source=rss-a7cd74ff6837------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e90df24141c</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[postgis]]></category>
            <dc:creator><![CDATA[João Salgado]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 14:47:09 GMT</pubDate>
            <atom:updated>2024-04-30T22:13:59.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oIPJdXvap2VztXhKgwVA9w.png" /></figure><p>It is very common to need to create products using map data. Perhaps the first thing that comes to our mind is Google Maps, Waze, Mapbox, etc. For the inattentive eye that needs to work with map data, it’s easy to think that we only need to use paid APIs from a few vendors. And well, they are right, we can do a lot of things using these APIs.</p><p>But what do you do when you need to store your own map data? Some examples:</p><ul><li>You work at an asset tracking company and your client wants to create geofences, so the client would like to know when an asset enters or leaves a location.</li><li>You work at a transportation route planning company, your client adds locations, plans and you have to create a visualization for them.</li><li>You work at a real estate agency and must add all the properties that the campaign manages to a map.</li></ul><p>There are dozens of examples, let’s get to what matters now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*D1PiCt9inwoJukLgDBjVig.gif" /></figure><h4>In this blog post, we will cover:</h4><ul><li>What’s geometric data?</li><li>Configuring Spring Boot</li><li>Mapping geometric data using Kotlin</li><li>How to store geometric data using PostgreSQL + Postgis</li><li>Bonus: Query to check if latitude and longitude are within a geometry</li></ul><h4>What’s geometric data?</h4><p>We can have different geometry formats: circle, line, point, rectangle and polygons, see the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*t30u3TTHoCjHlRFzuOdfeQ.png" /></figure><p>The problem is: how can I represent these types of data? This is not a string, number or boolean, it is more complex than that.</p><p>There are different ways to represent this data: JSON, GeoJSON, WKT, etc. For today we will cover <a href="https://geojson.org/">GeoJSON</a>, which is the most common use case. GeoJSON is JSON, but with a standard structure where we can define different geometry formats. So, with just one GeoJSON (or JSON) structure, we can represent circles, lines, points, rectangles and polygons. The basic structure is:</p><ul><li>A key called “<strong>type</strong>” defining the shape of the geometry</li><li>A key called “<strong>coordinates</strong>” with the points that construct the geometry</li></ul><p><strong>Point:</strong></p><pre>{<br>    &quot;type&quot;:&quot;Point&quot;,<br>    &quot;coordinates&quot;:[<br>       100.0,<br>       100.0<br>    ]<br>}</pre><p><strong>Line:</strong></p><pre>{<br>    &quot;type&quot;:&quot;LineString&quot;,<br>    &quot;coordinates&quot;:[<br>       [<br>          100.0,<br>          0.0<br>       ],<br>       [<br>          101.0,<br>          1.0<br>       ]<br>    ]<br>}</pre><p>Polygon, Circle, Rectangle (yes, you will use Polygon for circle and rectangle)</p><pre>{<br>    &quot;type&quot;:&quot;Polygon&quot;,<br>    &quot;coordinates&quot;:[<br>       [<br>          [<br>             100.0,<br>             0.0<br>          ],<br>          [<br>             101.0,<br>             0.0<br>          ],<br>          [<br>             101.0,<br>             1.0<br>          ],<br>          [<br>             100.0,<br>             1.0<br>          ],<br>          [<br>             100.0,<br>             0.0<br>          ]<br>       ]<br>    ]<br>}</pre><p>Ok, with that, now we know how to represent geometries and the payload we need to send to our API or receive from the API.</p><h4>Configuring Spring Boot</h4><p>Let’s get to the code and do basic operations using geometric data, first consider that I’m using Spring Boot 3.3.2 in the examples, with java 17. You can create something similar using <a href="https://start.spring.io/#!type=gradle-project-kotlin&amp;language=kotlin&amp;platformVersion=3.2.3&amp;packaging=jar&amp;jvmVersion=17&amp;groupId=com.example&amp;artifactId=demo&amp;name=demo&amp;description=Demo%20project%20for%20Spring%20Boot&amp;packageName=com.example.demo">spring initializr</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*ZEVZbE3HggYrLgEBmpND9Q.png" /></figure><p>Then we need to add some important dependencies to our build.gradle.kts.</p><pre>// omitted to illustrate<br>dependencies {<br>  implementation(&quot;org.locationtech.jts:jts-core:1.19.0&quot;)<br>  implementation(&quot;org.n52.jackson:jackson-datatype-jts:1.2.10&quot;)<br>  implementation(&quot;org.hibernate.orm:hibernate-spatial:6.4.4.Final&quot;)<br>}<br>// omitted to illustrate</pre><p>The first dependency (org.locationtech.jts:jts-core) will be responsable to provide us classes to represent a geometric object. The second one (org.n52.jackson:jackson-datatype-jts:1.2.10), will help us serialize and deserialize these objects. The last one (org.hibernate.orm:hibernate-spatial:6.4.4.Final), will be responsable to persist the geometry object in the database.</p><p>With these three dependencies, we can create a bean to serialize and deserialize geometric objects:</p><pre>package com.example.demo.infrastructure.config<br><br>import org.n52.jackson.datatype.jts.JtsModule<br>import org.springframework.context.annotation.Bean<br>import org.springframework.context.annotation.Configuration<br><br>@Configuration<br>class GeometryConfig {<br>    @Bean<br>    fun jtsModule(): JtsModule {<br>        return JtsModule()<br>    }<br>}</pre><h4>Mapping geometric data using Kotlin</h4><p>We can create an Entity to represent the data we would like to persist.</p><pre>package com.example.demo.domain<br><br>import jakarta.persistence.Column<br>import jakarta.persistence.Entity<br>import jakarta.persistence.Id<br>import jakarta.persistence.Table<br>import org.locationtech.jts.geom.Point<br>import org.locationtech.jts.geom.Polygon<br>import java.util.UUID<br><br>@Entity<br>@Table(name = &quot;geofences&quot;)<br>class Geofence(<br>    @Id<br>    var id: UUID,<br><br>    @Column(name = &quot;name&quot;, nullable = false)<br>    var name: String,<br><br>    @Column(name = &quot;geometry_polygon&quot;, columnDefinition = &quot;geometry(Polygon, 4326)&quot;, nullable = false)<br>    var geometryPolygon: Polygon,<br><br>    @Column(name = &quot;geometry_point&quot;, columnDefinition = &quot;geometry(Point, 4326)&quot;, nullable = false)<br>    var geometryPoint: Point,<br>)</pre><p>Notice this when we define two geometric objects, a point and a polygon. Also note that we use the columnDefinition with value geometry in the @Column annotation, this is specific to use with Postgresql, if you are going to use it with another database, you must check the corresponding documentation so that everything works well.</p><p>Note that we define a strange number “4326”, this number is about the spatial reference identifier (SRID).</p><blockquote>Every geometric shape has a spatial reference system associated with it, and each such reference system has a Spatial Reference System ID (<a href="https://www.cockroachlabs.com/docs/v23.2/architecture/glossary#srid">SRID</a>). The SRID is used to tell which spatial reference system will be used to interpret each spatial object.</blockquote><blockquote>A common SRID in use is 4326, which represents spatial data using longitude and latitude coordinates on the Earth’s surface as defined in the <a href="https://www.cockroachlabs.com/docs/v23.2/architecture/glossary#wgs84">WGS84</a> standard, which is also used for the <a href="https://wikipedia.org/wiki/Global_Positioning_System">Global Positioning System (GPS)</a>.</blockquote><h4>How to store geometric data using PostgreSQL + Postgis</h4><p>To work with PostgreSQL, we must install the <a href="https://postgis.net/">Postgis</a> extension, which is a very mature and performant extension for working with geometric data in PostgreSQL. How you install this extension depends on your infrastructure. Normally databases managed in the main cloud providers (AWS, GCP, AZURE, etc.) already have the extension installed and you should just enable it with the following script.</p><pre>-- You must have postgis installed on your server or machine to run this script<br>-- https://postgis.net/install/<br>CREATE EXTENSION IF NOT EXISTS postgis;<br>CREATE EXTENSION IF NOT EXISTS postgis_topology;</pre><p>With the extension installed and enabled, we just need to create our table to match our entity.</p><pre>CREATE TABLE IF NOT EXISTS geofences<br>(<br>  id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),<br>  name TEXT NOT NULL,<br><br>  geometry_polygon GEOMETRY(POLYGON, 4326) NOT NULL,<br>  geometry_point GEOMETRY(POINT, 4326) NOT NULL<br>);<br><br>CREATE INDEX geofences_geometry_polygon_idx ON geofences USING gist(geometry_polygon);</pre><p>Note that we created an index on the geometry column, this will help us create much more performant queries using a geospatial index.</p><p>Now, lets create a simple endpoint to receive our request to create our data.</p><p><strong>Controller:</strong></p><pre>package com.example.demo.infrastructure.api<br><br>import com.example.demo.application.CreateGeofenceUseCase<br>import com.example.demo.application.dto.CreateGeofenceRequest<br>import com.example.demo.application.dto.GeofenceResponse<br>import jakarta.validation.Valid<br>import org.springframework.http.*<br>import org.springframework.web.bind.annotation.*<br>import java.net.URI<br><br>@RestController<br>@RequestMapping(&quot;/geofences&quot;)<br>class GeofenceController(<br>    private val createGeofenceUseCase: CreateGeofenceUseCase<br>) {<br>    @PostMapping(<br>        consumes = [MediaType.APPLICATION_JSON_VALUE],<br>        produces = [MediaType.APPLICATION_JSON_VALUE],<br>    )<br>    fun create(<br>        @RequestBody @Valid<br>        requestBody: CreateGeofenceRequest,<br>    ): ResponseEntity&lt;GeofenceResponse&gt; {<br>        val geofenceResponse = createGeofenceUseCase(requestBody)<br><br>        return ResponseEntity<br>            .created(URI.create(&quot;/geofences/${geofenceResponse.id}&quot;))<br>            .body(geofenceResponse)<br>    }<br>}</pre><p><strong>Request body:</strong></p><pre>package com.example.demo.application.dto<br><br>import com.fasterxml.jackson.annotation.JsonProperty<br>import org.locationtech.jts.geom.Point<br>import org.locationtech.jts.geom.Polygon<br><br>data class CreateGeofenceRequest(<br>    @field:JsonProperty(&quot;name&quot;)<br>    var name: String,<br><br>    @field:JsonProperty(&quot;geometry_polygon&quot;)<br>    var geometryPolygon: Polygon,<br><br>    @field:JsonProperty(&quot;geometry_point&quot;)<br>    var geometryPoint: Point<br>)</pre><p><strong>Response body:</strong></p><pre>package com.example.demo.application.dto<br><br>import org.locationtech.jts.geom.Point<br>import org.locationtech.jts.geom.Polygon<br>import java.util.UUID<br><br>data class GeofenceResponse(<br>    val id: UUID,<br>    val name: String,<br>    val geometryPolygon: Polygon,<br>    val geometryPoint: Point<br>)</pre><p><strong>Use case:</strong></p><pre>package com.example.demo.application<br><br>import com.example.demo.application.dto.CreateGeofenceRequest<br>import com.example.demo.application.dto.GeofenceResponse<br>import com.example.demo.domain.Geofence<br>import com.example.demo.domain.GeofenceRepository<br>import jakarta.transaction.Transactional<br>import org.springframework.stereotype.Service<br><br>@Service<br>class CreateGeofenceUseCase(<br>    private val geofenceRepository: GeofenceRepository,<br>) {<br>    @Transactional<br>    operator fun invoke(requestBody: CreateGeofenceRequest): GeofenceResponse {<br>        val newGeofence = Geofence.new(<br>            name = requestBody.name,<br>            geometryPolygon = requestBody.geometryPolygon,<br>            geometryPoint = requestBody.geometryPoint<br>        )<br><br>        val geofence = geofenceRepository.save(newGeofence)<br><br>        return GeofenceResponse(<br>            id = geofence.id,<br>            name = geofence.name,<br>            geometryPolygon = geofence.geometryPolygon,<br>            geometryPoint = geofence.geometryPoint<br>        )<br>    }<br>}</pre><p><strong>Repository:</strong></p><pre>package com.example.demo.domain<br><br>import org.springframework.data.repository.CrudRepository<br>import org.springframework.stereotype.Repository<br>import java.util.UUID<br><br>@Repository<br>interface GeofenceRepository : CrudRepository&lt;Geofence, UUID&gt;</pre><p>And voila, you can now store geometric objects using Spring Boot 3, Kotlin and PostgreSQL.</p><h4>Bonus: Query to check if latitude and longitude are within a geometry</h4><p>Sometimes you will need to query geospatial data in your database, but this cannot be done using JPQL or JPA interface queries. You need to create native queries, so you can use the full power of the postgis extension.<br>For example, imagine you need to query all geometric objects that intersect a latitude and longitude, you can do this:</p><pre>@Repository<br>interface GeofenceRepository : CrudRepository&lt;Geofence, UUID&gt; {<br>    @Query(<br>        &quot;&quot;&quot;<br>            SELECT g.*<br>            FROM geofences g<br>            WHERE ST_Intersects(g.geometry_polygon, ST_SetSRID(ST_MakePoint(:lng, :lat), 4326))<br>        &quot;&quot;&quot;,<br>        nativeQuery = true<br>    )<br>    fun findAllByLngLat(lng: Double, lat: Double): List&lt;Geofence&gt;<br>}</pre><p>Postgis has dozens of functions that you can use to work with geospatial data, I recommend you learn more in the <a href="https://postgis.net/docs/reference.html">documentation</a>.</p><p>And that’s it guys, thanks for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ZuJQNdkzaT3IzdTVuLaFBQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e90df24141c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement a cron job in a multi-replica deployment using Spring Boot and Kotlin]]></title>
            <link>https://medium.com/@joao-slgd/how-to-implement-a-cron-job-in-a-multi-replica-deployment-using-spring-boot-and-kotlin-7c3b16aa2835?source=rss-a7cd74ff6837------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c3b16aa2835</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[shedlock]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[João Salgado]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 19:13:15 GMT</pubDate>
            <atom:updated>2024-04-30T22:13:32.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v4jG7gEjt_h4UVNM" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">Kenny Eliason</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine the following, I have my app running in production with 5 replicas. Each processing requests and consuming my queues perfectly!</p><p>My product manager gently knocks the door, walks in, and says, “Hey, our client would like to receive a report on last day’s sales at 9 a.m. every day.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*X3GLLyK1KCpsmDaQGT2j7g.gif" /></figure><p>Well, no problem. I got it.</p><p>Since we have some experience in software engineering, we all know that this problem is solved with <a href="https://en.wikipedia.org/wiki/Cron">cron</a> jobs. There are dozens of ways to solve this, we can use <a href="https://cronitor.io/guides/cron-jobs">crons on Linux</a>, on <a href="https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/">kubernetes</a>, crons with some framework that supports it, etc.</p><p>In my case, my application was using spring boot and this framework has great support for cron jobs using <a href="https://spring.io/guides/gs/scheduling-tasks">scheduling tasks</a>. It’s simple to configure, just enable the tool in the project with an <strong>@EnableScheduling</strong> annotation:</p><pre>@SpringBootApplication<br>@EnableScheduling<br>class DemoApplication<br><br>fun main(args: Array&lt;String&gt;) {<br> runApplication&lt;DemoApplication&gt;(*args)<br>}</pre><p>And create a class with the cron job:</p><pre>@Component<br>class Cron {<br>    companion object {<br>        const val EVERY_DAY_AT_9= &quot;0 9 * * * ?&quot;<br>    }<br><br>    private val logger: Logger = LoggerFactory.getLogger(this::class.java)<br><br>    @Scheduled(cron = EVERY_DAY_AT_9)<br>    operator fun invoke() {<br>        logger.info(&quot;Executing cron...&quot;)<br><br>    }<br>}</pre><p>Very simple, with this, our cron is running and we just need to implement the logic to generate our report. What happens if I put this code into production? Well, at 9 am every day, we will send the report to our client…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ZuJQNdkzaT3IzdTVuLaFBQ.gif" /></figure><p>5 times, 5 reports repeated at the same time…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*rhGMH4c8Z_C-ecfqgs-rjw.gif" /></figure><p>For the most attentive readers, I said previously that I have 5 replicas of my application running in production. So if each replica runs my cron at the same time at 9 am, that means we build and send the same report 5 times.</p><p>We don’t want to do that, right? We have a few options:</p><ul><li><strong>A separate service with just one replica:</strong> Great option, I will only process once as I only have one replica. But it’s another deployment, another service in production, another pipeline deployment, another application to maintain, monitor and spend money on.</li><li><strong>A cron job in another tool like linux, k8s, etc:</strong> As I know how to use these tools and easily integrate with external resources (database, apis, etc), it works.</li><li><strong>A lock mecanism in the app:</strong> So if I have 5 replicas, just one will execute my cron and the others will not.</li></ul><p>I like all the options, but the last one is very interesting. I will use the same application and have access to everything I already build, my classes, my repositories, etc. Well, here comes <a href="https://github.com/lukas-krecan/ShedLock">ShedLock</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*58Nm4_khwp8VmWVNzax1sA.gif" /></figure><blockquote>ShedLock makes sure that your scheduled tasks are executed at most once at the same time. If a task is being executed on one node, it acquires a lock which prevents execution of the same task from another node (or thread). Please note, that if one task is already being executed on one node, execution on other nodes does not wait, it is simply skipped.</blockquote><p>Well, I don’t think I need to say anything more about this, let’s get to the implementation!</p><pre>// omitted to illustrate<br>dependencies {<br> // omitted to illustrate<br> implementation(&quot;net.javacrumbs.shedlock:shedlock-spring:5.10.2&quot;)<br> implementation(&quot;net.javacrumbs.shedlock:shedlock-provider-jdbc-template:5.10.2&quot;)<br>}<br>// omitted to illustrate</pre><p>The first dependency is the main shedlock library, the second is where we will do the locking. In my case I used PostgreSQL but we have many options: MongoDB, Redis, Cassandra, etc.</p><p>For postgres, we must also define the table where we will maintain the lock structure:</p><pre>CREATE TABLE shedlock (<br>  name VARCHAR(64),<br>  lock_until TIMESTAMP(3) NULL,<br>  locked_at TIMESTAMP(3) NULL,<br>  locked_by VARCHAR(255),<br>  PRIMARY KEY (name)<br>);</pre><p>Now, we enable automatic configuration for this dependency:</p><pre>@SpringBootApplication<br>@EnableScheduling<br>@EnableSchedulerLock<br>class DemoApplication<br><br>fun main(args: Array&lt;String&gt;) {<br> runApplication&lt;DemoApplication&gt;(*args)<br>}</pre><p>We config the lock provider:</p><pre>@Configuration<br>class SchedulerConfig {<br>    @Bean<br>    fun lockProvider(dataSource: DataSource): LockProvider {<br>        return JdbcTemplateLockProvider(dataSource)<br>    }<br>}</pre><p>And finally, in our cron, we also define that we will use the lock with the annotation <strong>@SchedulerLock(name = “cron_invoke”)</strong></p><pre>@Component<br>class Cron {<br>    companion object {<br>        const val EVERY_DAY_AT_9= &quot;0 9 * * * ?&quot;<br>    }<br><br>    private val logger: Logger = LoggerFactory.getLogger(this::class.java)<br><br>    @Scheduled(cron = EVERY_DAY_AT_9)<br>    @SchedulerLock(name = &quot;cron_invoke&quot;)<br>    operator fun invoke() {<br>        logger.info(&quot;Executing cron...&quot;)<br><br>    }<br>}</pre><p>The “name” parameter in the annotation must be unique in the project. Therefore, if we have more than one cron job, we must have different names.</p><p>And that’s it, our cron will be performed just once and our custumer will only receive one report as expected!</p><p>Thanks for your reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*a1r7xWKVKWIQ3vqP4HxjVQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c3b16aa2835" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring boot + kotlin + multiple @FeignClient]]></title>
            <link>https://medium.com/@joao-slgd/spring-boot-kotlin-multiple-feignclient-2694407944d2?source=rss-a7cd74ff6837------2</link>
            <guid isPermaLink="false">https://medium.com/p/2694407944d2</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[João Salgado]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 19:02:04 GMT</pubDate>
            <atom:updated>2024-05-02T23:36:56.881Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot + Kotlin + Multiple @FeignClient</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_fEjxkn_o8_yuPwM" /><figcaption>Photo by <a href="https://unsplash.com/@hharritt?utm_source=medium&amp;utm_medium=referral">Hunter Harritt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I was developing my API and needed to integrate with a microservice. Very easy, I’ve done this several times using Spring boot <a href="https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html">Feign Clients</a>. However, something was wrong with the authentication and it confused me.</p><p>I received an error about my credentials, but when making the same request in <a href="https://www.postman.com/">Postman</a> everything worked fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*d0ThC3rlPtNvXGwXjLyQEA.gif" /></figure><p>For those who don’t know:</p><blockquote><a href="https://github.com/Netflix/feign">Feign</a> is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it.</blockquote><p>In other words, we can easily integrate our API with another<br>API, abstracting all the complexity of HTTP using Feign clients (thanks Spring Boot).</p><p>Until then, I had done the traditional implementation, I added the dependency to the project:</p><pre>// omitted to illustrate<br>dependencies {<br> implementation(&quot;org.springframework.cloud:spring-cloud-starter-openfeign&quot;)<br>  // omitted to illustrate<br>}<br>// omitted to illustrate</pre><p>I declared the use of the dependency, this is important to spring boot auto configurate the dependency in our project:</p><pre>@SpringBootApplication<br>@EnableFeignClients<br>class application<br><br>fun main(args: Array&lt;String&gt; {<br>  runApplication&lt;Application&gt;(*args)<br>}</pre><p>I created my integration interface. With this, simply inject this interface into our service or use case, and call the method to integrate with the other API:</p><pre>@FeignClient(name = &quot;product-gateway&quot;, url = &quot;private.api.com&quot;, configuration = [ProductApiInterceptor::class])<br>interface ProductGateway {<br>  <br>  @RequestMapping(<br>    method = [RequestMehod.POST],<br>    value = [&quot;/products&quot;],<br>    consumes = [&quot;application/json&quot;],<br>    headers = [&quot;requester-name=my-api-request&quot;]<br>  )<br>  fun createProduct(request: CreateProductRequest): CreateProductResponse?<br><br>}</pre><p>And I implemented my authentication method, where I take the token from the current request and use it to authenticate the other API using the header “authorization”. In this scenario, my API and the API that I would like to consume use the same authentication method:</p><pre>@Configuration<br>class ProductConfig {<br>  @Bean<br>  fun productApiInterceptor(): ProductApiInterceptor{<br>    return ProductApiInterceptor()<br>  } <br>}</pre><pre>class ProductApiInterceptor: RequestInterceptor {<br>  override fun apply(template: RequestTemplate?) {<br>    val requestAttr = (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes)<br>    val apiToken = requestAttr.request.getHeader(&quot;authorization&quot;)<br>    template?.header(&quot;authorization&quot;, apiToken)<br>  }<br>}</pre><p>With this code, I can normally connect to APIs, but this was not happening as expected. The request always received an authentication error. I looked deeper and noticed that the project had other interfaces using <a href="http://twitter.com/FeignClient">@FeignClient</a>, with other authentication methods. This gave me an alert, could it be related?</p><p>The other authentication method also overwrites the “authorization” header and this could be causing a problem.</p><p>Here is a code snippet to exemplify the other FeignClient and the code authentication method.</p><pre>@FeignClient(name = &quot;order-gateway&quot;, url = &quot;private.api.com&quot;, configuration = [OrderApiInterceptor::class])<br>interface OrderGateway {<br>  <br>  @RequestMapping(<br>    method = [RequestMehod.GET],<br>    value = [&quot;/orders&quot;],<br>    consumes = [&quot;application/json&quot;],<br>    headers = [&quot;requester-name=my-api-request&quot;]<br>  )<br>  fun getOrders(orderId: UUID): OrderResponse?<br><br>}</pre><pre>@Configuration<br>class OrderConfig {<br>  @Bean<br>  fun orderApiInterceptor(): OrderApiInterceptor{<br>    return OrderApiInterceptor()<br>  } <br>}</pre><pre>class OrderApiInterceptor: RequestInterceptor(<br>  @Value(&quot;\${order.api.token}&quot;)<br>  private val apiToken: String? = null<br>) {<br>  override fun apply(template: RequestTemplate?) {<br>    template?.header(&quot;authorization&quot;, apiToken)<br>  }<br>}</pre><p>In this case, the authentication method was being done through an API token, a different type of authentication.</p><p>After investigating a little further, I discovered that authentication beans were inherited in context becasue I was using the same API url in my clients (private.api.com), and that in order to correctly distinguish between authentication methods, it was necessary to explicitly state that we do not want inheritance:</p><pre>@Configuration<br>class FeignConfig {<br><br>  @Bean<br>  fun feignClientConfigurer(): FeignClientConfigurer {<br>    return object : FeignClientConfigurer {<br>      override fun inheritParentConfiguration(): Boolean {<br>        return false<br>      }<br>    }<br>  }<br><br>  @Bean<br>  fun orderApiInterceptor(): OrderApiInterceptor{<br>    return OrderApiInterceptor()<br>  }<br><br>  @Bean<br>  fun productApiInterceptor(): ProductApiInterceptor{<br>    return ProductApiInterceptor()<br>  }<br><br>}</pre><p>And with that, the integrations started to work normally, each with its own authentication method!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*t7ACGrD71aGPIPHctrlVAw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2694407944d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to design a system for millions of users]]></title>
            <link>https://medium.com/@joao-slgd/como-projetar-um-sistema-para-milh%C3%B5es-de-usu%C3%A1rios-42ab7de4eb60?source=rss-a7cd74ff6837------2</link>
            <guid isPermaLink="false">https://medium.com/p/42ab7de4eb60</guid>
            <category><![CDATA[engenharia-de-software]]></category>
            <category><![CDATA[escalabilidade]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[sistemas-distribuidos]]></category>
            <dc:creator><![CDATA[João Salgado]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 13:55:12 GMT</pubDate>
            <atom:updated>2024-02-24T19:35:31.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mGf9OaQ66BdnRNsq" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is not simple to design a system with the ability to scale its use to millions of users. It’s a super challenge from a software architecture point of view.</p><p>Topics covered in this article:</p><ul><li>Scaling your frontend</li><li>Scaling your backend</li><li>Scaling the database</li><li>Cache</li><li>DNS, geoDNS</li></ul><p>Topics that will not be covered in depth in this article</p><ul><li>Application resilience</li><li>High Availability</li><li>Fault tolerance</li><li>Observability</li></ul><blockquote>We can talk more about these topics in the future!</blockquote><p>Let’s go!</p><h3>Basic Application</h3><p>Initially I would like to present the architecture of a basic system, the way most of us start. This is probably the simplest way to create a system and host it on just 1 server.</p><ul><li>A frontend running inside an Apache or Tomcat.</li><li>A backend, in this case APIs, also running on Apache or Tomcat.</li><li>A database like PostgreSQL or MySQL.</li></ul><blockquote>For example purposes, let’s consider that our frontend and our backend are different applications.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*gnoMv7VmKABkF5-G2HZvIw.png" /><figcaption>Frontend, backend and database on the same server</figcaption></figure><p>There are some disadvantages with this architecture.</p><ul><li>If the database fails, the system fails</li><li>If our server fails, the entire system fails</li></ul><p>In this case, we lack redundancy and fault tolerance.</p><h3>Types of scalability</h3><p>There are several reasons why a system needs to scale, such as an increase in data volume, an increase in the number of requests or transactions and a growth in the number of users.</p><p>Scalability is directly related to the system’s ability to support more users, clients, data and requests without compromising the user experience by adding more computing resources.</p><p>Therefore, the next step is to define which type of scalability makes the most sense for the application. There are 2 types of scalability: vertical (scale-up) and horizontal (scale-out).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*M3_rr08ejazdFGSQmReaiQ.png" /><figcaption>Vertical Scale VS Horizontal Scale</figcaption></figure><h3>Vertical scale (scale-up)</h3><p>It refers to increasing the amount of resources available on the same server, expanding its capacity to support more processes. Normally it involves adding more CPU or RAM memory to the server, but it is not limited to that and can also be:</p><ul><li>Improve IR speed by swapping HD for SSD.</li><li>Switch to a server with more processors.</li><li>Increase network throughput by improving existing interfaces or adding new ones.</li></ul><p>Scaling the system vertically is usually a great option for small systems, where the hardware upgrade is affordable. However, it has some limitations:</p><ul><li>It is almost impossible to use the vertical scale infinitely.</li><li>When we upgrade certain server components, such as RAM, we need to restart the server. If the system is on just one server, it will inevitably be unavailable.</li><li>Powerful machines tend to cost much more than smaller, more popular machines.</li><li>If you are running several applications on the same server, the upgrade will be done for all applications. We are unable to direct resources to the services most needed.</li></ul><p>It also fits into a vertical scale, any optimizations that are made in the software, such as optimizing queries and application code.</p><h3>What if we use more than one server?</h3><p>With the growth of the application and the number of users, using just one server is not enough. We can separate our single server into several others, so we can distribute the load and scale each resource individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*5iTeEZ9qYXt_hM2aZYlngw.png" /><figcaption>Separating applications across multiple servers is healthy.</figcaption></figure><p>This architecture brings some advantages:</p><ul><li>We can scale each server according to its characteristics.</li><li>Each server can scale independently of another.</li></ul><h3>Horizontal scale (scale-out)</h3><p>In this scenario, we need to add more machines or services to our ecosystem. It is more difficult to do the horizontal scale because it must be thought of from the beginning, and must be maintained until the end.</p><p>This type of scale usually costs more initially as we need several servers even to perform basic tasks, but as the application and usage grows, it usually pays for itself very quickly. Some features to consider:</p><ul><li>Increasing the number of servers means increasing maintenance work on them.</li><li>The implemented code must, from the beginning, allow parallel processing and load distribution between multiple servers.</li></ul><h3>Load distribution and load balancer</h3><p>A load balancer is a service specialized in distributing traffic/requests across a cluster of servers in order to improve the system’s responsiveness and availability. It can be used in apis, frontends, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*n9DSr1oA6p0zSxv9YmpAJA.png" /><figcaption>Balancing traffic between servers</figcaption></figure><p>Using a load balancer means you can more easily tolerate application failures and increase the availability of your system.</p><ul><li>If server 1 is unavailable, all traffic can be redirected to servers 2 and 3. The service will not go offline. You can add as many servers as you need to have a quality of service good enough for the number of accesses.</li><li>When the traffic increases, you can increase the number of servers. And when it drops, it can be reduced without compromising the quality of the service.</li></ul><p>There are several load balancing strategies that can be used, the main ones are:</p><ul><li><strong>Fewer connections</strong>: The server with the fewest connections receives the request.</li><li><strong>Fastest response</strong>: The server with the best response time receives the request.</li><li><strong>Round Robin</strong>: Each server receives a request, sequentially.</li><li><strong>IP Hash</strong>: A hash of the client’s IP is used to redirect to a specific server.</li><li><strong>Weighted</strong>: The more powerful server will receive more requests and the smaller servers will receive fewer.</li></ul><p>Ultimately, the best way to load balance requests is to add more machines (hardware) to the cluster.</p><p>But using a load balancer via software is a cheap alternative when compared to hardware. They operate at layer 3 (network) and 7 (application) of the OSI model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*k4y4JeginVbjH3PkV4Mx4w.png" /><figcaption>OSI model</figcaption></figure><ul><li>At layer 3, the load balancer uses the information provided by TCP. At this layer, balancing is done without looking at the content of the request.</li><li>At layer 7, the load balancer uses information from the request, such as cookies, headers, query strings, etc.</li></ul><h3>Scaling the frontend and the backend</h3><p>To scale the frontend and backend, we followed the horizontal scaling model with multiple servers and a load balancer distributing the load between the services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*1HyB40QvVQn84mgaX6EceQ.png" /><figcaption>Balancing traffic between your servers in a stateless architecture</figcaption></figure><p>To take full advantage of load balancer load distribution, you need to move user session data from the web tier and store it in a SQL or NoSQL database. This is the so-called stateless architecture.</p><p>Whenever possible, do not use stateful architecture, it limits your scalability, reduces your availability and can increase your cost.</p><h3>Database</h3><p>There are 2 main types of databases: SQL and NoSQL. These 2 types have significant differences with regard to the type of data they are recommended to store, the storage method they use and the way they were constructed.</p><h3>SQL</h3><p>It’s the most popular type of database among beginners and is often the most obvious solution. Storage is in the format of rows and columns, with each row containing all the information about some entity and the columns containing the entity’s unitary data.</p><p>It is recommended in scenarios that your data is well structured and that the consistency of your data is important. Furthermore, it facilitates data extraction due to its chain of relationships.</p><p>We typically relate the use of a SQL database to ACID.</p><ul><li><strong>Atomicity</strong>: Each transaction in the database must be indivisible, even if several operations take place in it. All operations must be executed to completion for the transaction to be persisted. In case of failure of any operation, none of the previous partial operations must be persisted.</li><li><strong>Consistency</strong>: The transaction must respect the integrity of the data. All transactions in the database must be valid according to previously defined rules, such as restrictions on unique keys, numeric values and field sizes.</li><li><strong>Isolation</strong>: Avoid parallel transactions as much as possible from interfering with each other. One user cannot read a record while another is changing it.</li><li><strong>Durability</strong>: The effects of a successful transaction must persist in the database even in cases of error, crashes or power outages.</li></ul><p>MySQL, Oracle, MS SQL Server, SQLite, PostgreSQL, and MariaDB are some of the most popular SQL databases.</p><h3>NoSQL</h3><p>While SQL databases are very similar to each other, NoSQL databases have differences that can be categorized into 5 main categories:</p><h4>Key-Value database</h4><p>The database is made up of a set of keys and values. The key is a name for a certain value.</p><p>Some of the best known are Redis, MemcacheD and Dynamo.</p><h4>Document Database</h4><p>In this model, data is stored as “documents”. This model is highly flexible and does not require pre-assembled columns. These documents are grouped by collections and each document can have a completely different structure from the other.</p><p>The best-known database in this format is MongoDB.</p><h4>Database of Columns</h4><p>In this model we have column families, which are containers for rows. Unlike SQL, you don’t need to know all the columns right away and the rows don’t need to have the same number of columns.</p><p>They are commonly used to analyze large amounts of data. The best-known database for this model is Cassandra.</p><h4>Graph Database</h4><p>Stores data in the form of a graph. That is, here the data is arranged in the format of arcs connected by edges. We can define it as a set of lines connected by vertices as well.</p><p>The graph model is advantageous for complex searches, as latency and performance promise to be lower than in other models.</p><p>One of the best known is Neo4J.</p><h4>Archive Database</h4><p>They are very similar to the key-value database, but they are more recommended for storing images, videos and files in general.</p><p>We can mention, for example, Amazon S3, Windows Azure Blob Storage, Google Cloud Storage.</p><h4>Which database to choose?</h4><p>There is no silver bullet, it is necessary to analyze each scenario and understand which fits best. In general, when the system grows, it is common to use several types.</p><h3>Scaling your SQL relational database</h3><p>Looking at our base system, we opted for PostgreSQL, a relational database to save our data. Relational databases have some challenges in terms of scalability. And when we think about its scalability, we typically opt for some of the following 7 techniques:</p><h4>Master-Slave Replication</h4><p>In this technique, data from a main database (master) is replicated to one or more secondary databases (slave). Data from the master database is propagated to all other databases until they are all consistent.</p><p>Write operations must always be performed on the master database, while read operations can be performed on either database.</p><p>Despite being a viable technique, it has some limitations:</p><ul><li>If the master database becomes unavailable, the data will still be available on the slaves, but write operations cannot be performed until the master database returns.</li><li>Extra configuration is required to promote a slave database to a master.</li></ul><p>Data replication can be done in two ways:</p><ul><li><strong>Synchronous</strong>: The writing operation is only consolidated when all servers have received the information (distributed transaction), without inconsistency in the data if a problem occurs.</li><li><strong>Asynchronous</strong>: Propagation to servers is done asynchronously. Typically synchronous replication is slower than asynchronous replication.</li></ul><h4>Master-Master Replication</h4><p>Again we have several database servers where replication is done. The difference is that all servers act as masters at the same time, subsequently replicating to other servers.</p><p>Read and write operations can be done on any server.</p><h4>Federation</h4><p>In this method, the database is divided by function. Instead of a single monolith database with all the tables and functions, you can break it into several smaller databases with specific functions.</p><p>To use databases, you use software that allows you to access all databases as if they were one. This virtual database captures data from other databases and converts it to a common access model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*BjzjRVEW3QvoWniLo_B3nw.png" /><figcaption>We break down our monolithic database by function</figcaption></figure><p>Smaller databases mean more data can be loaded into memory. In addition to the distribution of database, they can receive writing in parallel, increasing throughput.</p><h4>Sharding</h4><p>Sharding is the technique of partitioning a large database into smaller pieces so that each database manages a piece of the data.</p><p>In an ideal scenario, different users would access different databases.</p><ul><li>A user would only access one of the database servers. This partitioning would ensure faster server responses.</li><li>The load is well balanced between servers. If we have 5 databases, each one will receive 20% of the traffic.</li></ul><p>This strategy helps with performance, availability and load balancing.</p><p>This partitioning can be done in several ways:</p><h4>Horizontal partitioning (sharding)</h4><p>In this technique, we separate the rows into different tables. For example, if we have a table containing 3000 films, we can place films with an id less than 1000 in one table, 1000 to 2000 in another table and 2001 to 3000 in a third table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*jGsguUWh80iQ01hXXFSJZA.png" /><figcaption>We put a range of films from different tables</figcaption></figure><h4>Vertical partitioning (sharding)</h4><p>In this case, we divide our most related data into specific servers. Returning to the cinema example, we can store user data along with their preferred film genre on one server, movie theaters along with weekly programming on another server and films along with the number of people who watched them on a third server.</p><p>Keep in mind that sharding has some known issues:</p><ul><li>Database joins become more costly and sometimes unfeasible to do.</li><li>Changing the database’s schema can be very costly.</li><li>Sharding can compromise the database’s referential integrity.</li></ul><h4>Denormalization</h4><p>It seeks to improve the database’s reading performance at the expense of writing. Redundant copies of data are written to multiple tables to avoid cumbersome joins.</p><p>Since distributed techniques were used to store data, performing joins across different servers tends to be quite complex. Performing denormalization can minimize these impacts.</p><p>In most systems, the read operation is more frequent than the write operation, so depending on the join performed, the operation can be very slow and complex. There are systems in which reading far exceeds writing, on scales of 100:1 or even 1000:1.</p><h3>Cache</h3><p>Adding cache on servers can prevent a read from the database, a web page from being compiled again or a static file from being fetched again. Thus reducing server response and loading time.</p><p>The cache will allow you to make the best use of your available resources, and can be applied at different layers of the application such as the web, network and server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*y1x3WU_DE3ekTCB3_VBaHQ.png" /><figcaption>The operation performed in the cache is much faster than in the database</figcaption></figure><p>Let’s take a practical example, imagine that your website’s home page takes an average of 100ms to load for the user and that the time is divided as follows:</p><ul><li>10ms HTTP Request</li><li>5ms Load Balancer</li><li>20ms of Framework Backend</li><li>30ms from Database</li><li>25ms to generate HTML</li><li>10ms HTTP Response</li></ul><p><strong>Total: 100ms</strong></p><p>With caching, we could have the following scenario:</p><ul><li>10ms HTTP Request</li><li>5ms Load Balancer</li><li>20ms of Framework Backend</li><li>10ms from Cache</li><li>10ms HTTP Response</li></ul><p><strong>Total: 55ms</strong></p><p>The scenario is theoretical, but in this case we exchange the database search and HTML generation for the cache search. In isolation, we might think that it doesn’t make a difference, but in scenarios with thousands of requests per second, reducing the response time by almost half could be the difference between having the system available or not.</p><h3>Content Delivery Network (CDN)</h3><p>CND servers cache a copy of typically static content, such as images, JavaScript files, HTML, etc. And they distribute them from the location closest to the user.</p><p>This technique helps with availability and loading performance, as the content is available in different places and the user receives the data from the closest server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*xWjzTYZjqmqPIOZM4vn3RA.png" /><figcaption>Using CND improves performance and data availability</figcaption></figure><p>CND makes frequent requests to the application server to understand whether its cache should be updated or not.</p><h3>Global System</h3><p>Thinking about making your system available to the world, it is common to think that your system will also be distributed in data centers around the world. Your operation from here becomes much more complex and you cannot afford the luxury of a request from the other side of the world landing in a data center in Brazil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Jb6OdyHuXW-yxYE" /><figcaption>Photo by <a href="https://unsplash.com/@jeremybezanger?utm_source=medium&amp;utm_medium=referral">Jeremy Bezanger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Requests need to find a route to the nearest data center and this is done via GeoDNS. GeoDNS is a DNS service that allows domain names to be resolved to IP based on the user’s location. A user in Brazil will possibly connect to a different IP than a user in Asia.</p><h3>Final Design</h3><p>Using a stateless architecture, with load balancer, lots of caching, hosting in multiple data centers, CDN and scaling the database via sharding, we were able to support millions of users in our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*kO0Vu4bi1XeKxHWL3Lwm8A.png" /><figcaption>Scaling a platform is an ongoing process</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42ab7de4eb60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns vs. Homemade Solutions]]></title>
            <link>https://medium.com/@joao-slgd/design-patterns-vs-solu%C3%A7%C3%B5es-caseiras-6b733e220d80?source=rss-a7cd74ff6837------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b733e220d80</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[João Salgado]]></dc:creator>
            <pubDate>Mon, 15 Nov 2021 13:16:10 GMT</pubDate>
            <atom:updated>2024-02-24T19:16:22.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2OtyW-eN5Fj3opTv" /><figcaption>Photo by <a href="https://unsplash.com/@barnimages?utm_source=medium&amp;utm_medium=referral">Barn Images</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Creating simple and robust solutions is one of the biggest challenges we face as software engineers. Engineering is an intellectual work and, therefore, the same problem given to 5 engineers can generate 5 very different solutions.</p><p>That said, we have a huge challenge. How can we solve a problem in a simple way? That scales as the system grows? That doesn’t create a pull request (PR) that’s impossible to review? That we don’t create the wheel again? Anxiety starts to hit.</p><p>It is a fact that there is no final answer that solves all problems. But the good news for us is that we have somewhere to start.</p><h3>Homemade solutions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mv0X5m3TvATBd0tk" /><figcaption>Photo by <a href="https://unsplash.com/@micheile?utm_source=medium&amp;utm_medium=referral">Visual Stories || Micheile</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It’s natural that as we pursue our career as engineers, we gain more maturity and knowledge about a different set of problems, as my old father would say: you eat more salt.</p><p>And it is common that in the early stages, with creativity at its peak and with that incredible world of programming to be explored, engineers seek to create new things, their own solutions and even their own framework.</p><p>Who has never come across that painful maintenance solution created just 1 year ago, a library that cannot be found on the internet, a completely personalized authentication system, or even a completely original encryption algorithm.</p><p>Ahhh so you’re saying we should suppress the creativity of engineers and put them on an assembly line? It’s not that. There is room for creation, but we must always take into consideration whether we are reinventing the wheel once again. If the problem has not been resolved before, by other people. It is likely that for any new, home-made solution we want to implement, there are already established ones available on the internet.</p><h3>Design Patterns</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LKwhqL9wInEjiPmf" /><figcaption>Photo by <a href="https://unsplash.com/@leonardoeron?utm_source=medium&amp;utm_medium=referral">Leonardo Ramos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If we look at the pyramids in the desert, we notice that they are not identical, not the same size and quite possibly do not have the same number of stones, but they still have a pattern between them.</p><p>The fact is that standardization is easily recognized among the most diverse people. And thanks to this standardization, if you want to build your own pyramid, you already have a reference on where to start.</p><p>Design patterns in software development work the same way. They are generalist and well-tested solutions to recurring problems in an engineer’s daily life. It’s not ready-made code or one of those modern frameworks, but rather a high-level definition of how a problem can be solved.</p><p>Additionally, design patterns are a common language that you and your team can use to communicate more effectively. When your peer sees the implementation of a singleton in your PR, there will be no need to explain what a singleton is or the idea behind it, your code will be more readable.</p><p>But let’s not fool ourselves, they are not a silver bullet. It is necessary to analyze each scenario to understand when and which one should be used. Often the answer will be to not use any. To identify whether it makes sense to use it in a given scenario, we can keep two things in mind:</p><ul><li><strong>Motivation</strong>: We must be very clear about the problem encountered and the solution that the standard brings as a resolution. It is important to be clear about what justifies implementing the standard.</li><li><strong>Consequences</strong>: It may happen that, when implementing a pattern, we solve a problem but make something else difficult. Care must be taken to ensure that the complexity does not become greater than the applicability.</li></ul><p>To make a good decision, it is necessary to study the most diverse types of design patterns and understand what fits in each context. Therefore, I leave you with a useful but not extensive guide on where to start:</p><ul><li><strong>Object orientation</strong>: <a href="https://refactoring.guru/design-patterns/catalog">https://refactoring.guru/design-patterns/catalog</a></li><li><strong>Microservices:</strong> <a href="https://microservices.io/">https://microservices.io</a></li><li><strong>Concurrency:</strong> <a href="https://www.baeldung.com/concurrency-principles-patterns">https://www.baeldung.com/concurrency-principles-patterns</a></li><li><strong>Database and microservices: </strong><a href="https://medium.com/design-microservices-architecture-with-patterns/microservices-database-management-patterns-and-principles-9121e25619f1">https://medium.com/design-microservices-architecture-with-patterns/microservices-database-management-patterns-and-principles-9121e25619f1</a></li><li><strong>Front-end:</strong><a href="https://azeynalli1990.medium.com/software-architecture-patterns-for-front-end-development-9e43e43cdfb3"> </a><a href="https://azeynalli1990.medium.com/software-architecture-patterns-for-front-end-development-9e43e43cdfb3">https://azeynalli1990.medium.com/software-architecture-patterns-for-front-end-development-9e43e43cdfb3</a></li></ul><p>So, before implementing that super creative solution to the problem you are experiencing, it is important to reflect on whether there is already a stable solution on the market.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b733e220d80" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>