<?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 Apoorv Tyagi on Medium]]></title>
        <description><![CDATA[Stories by Apoorv Tyagi on Medium]]></description>
        <link>https://medium.com/@apoorvtyagi?source=rss-f4730edde1e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*B6ucBhf1L1s4eKFMBP2AHQ.jpeg</url>
            <title>Stories by Apoorv Tyagi on Medium</title>
            <link>https://medium.com/@apoorvtyagi?source=rss-f4730edde1e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:40:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@apoorvtyagi/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[How to Size Java Database Connection Pools in Kubernetes]]></title>
            <link>https://levelup.gitconnected.com/how-to-size-java-database-connection-pools-in-kubernetes-d95d778693d6?source=rss-f4730edde1e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d95d778693d6</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[database-design]]></category>
            <dc:creator><![CDATA[Apoorv Tyagi]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 18:46:36 GMT</pubDate>
            <atom:updated>2026-10-05T15:51:50.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23u5gyAD1BG7UY1Z8AZUqw.jpeg" /></figure><h3>Introduction</h3><p>I was reviewing a PR at work a month ago where a new application was setting up its database service, and I saw the connection pool properties, which made me think about how a small configuration looks in a single file, yet how destructive it can be at scale.</p><p>A database connection pool in Java looks like a small configuration:</p><pre>spring: <br>  datasource: <br>    hikari: <br>      maximum-pool-size: 10</pre><p>Add a Kubernetes microservices environment, and that setting is not small at all.</p><p>It means: <strong>10 database connections per pod</strong></p><p>If the service runs 20 pods during peak traffic, the database can see:</p><p><strong>20 pods x 10 connections = 200 possible connections</strong></p><p>If a rolling deployment temporarily creates extra pods, or if a canary version runs beside the main deployment, the number can be higher.</p><p>That is the core mental model we will be discussing:</p><blockquote><em>A Java connection pool is local to one pod, but the database pays the cost of all pools across all pods.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*telqdiOe4HTHI73I.png" /></figure><p>This post tries to explain how to size a Java JDBC connection pool in Kubernetes, how to choose maximumPoolSize, how to choose minimumIdle, how to reason about idleTimeout, and how to validate the settings in production.</p><p>The examples use Spring Boot with HikariCP because that is the common default stack for modern Java services. The same thinking applies to other JDBC pools.</p><h3>1. What a connection pool really does</h3><p>A connection pool has two jobs.</p><ol><li>First, it is a cache. Creating a database connection is expensive. The application may need to create a TCP connection, authenticate, initialize session state, and allocate memory on the database side. <strong>A pool keeps ready-to-use connections so each request does not pay that cost</strong>.</li><li>Second, and more importantly, <strong>it limits how many concurrent database operations one pod can send to the database</strong>.</li></ol><p>A larger pool does not always make a service faster. Once the database is already saturated, adding more connections often increases queueing, lock contention, memory pressure, and context switching.</p><blockquote><em>Think of the pool like the number of checkout counters at a store. Too few counters and customers wait unnecessarily. Too many counters, and the store does not magically get more cashiers or shelves.</em></blockquote><p>The goal is not to make the pool as large as possible. The goal is to use the smallest pool that keeps the database &amp; application healthy while serving request SLAs.</p><p>HikariCP’s own pool-sizing guidance is intentionally conservative: it emphasizes that optimal pools are usually much smaller than people expect and gives the classic starting point of approximately (core_count * 2) + effective_spindle_count active connections for database throughput testing. (See the references at the end for the official HikariCP pool-sizing page)</p><blockquote><em>In the context of database connection pool sizing (like the HikariCP formula), </em><em>effective_spindle_count is essentially a measure of how many concurrent I/O request your server can manage.</em></blockquote><blockquote><em>Rotating harddisks can only handle one I/O request at a time. If you have 16, your system can handle 16 I/O requests at the same time.</em></blockquote><blockquote><em>The mentioned rule of thumb is no longer valid for SSDs. As they can typically handle several parallel I/O requests at the same time.</em></blockquote><blockquote><em>Today the database is often CPU-bound, memory-bound, or lock-bound long before storage becomes the limiting factor.</em></blockquote><p>This is a starting point for benchmarking and not a universal production formula.</p><h3>2. Kubernetes changes the sizing problem</h3><p>In a single JVM, the connection pool is easy to visualize: one application process → one connection pool → one database</p><p>In Kubernetes, the shape is different: many pods → many private pools → one shared database</p><p>If each pod has a pool of 10 and Kubernetes runs 12 pods, the service can open up to 120 database connections.</p><p>That is only the steady-state number. The real upper bound must include autoscaling, rolling updates, canary deployments, workers, jobs, and terminating pods.</p><p>Kubernetes Horizontal Pod Autoscaling adds more pods to match demand, and a Deployment rolling update can create pods above the desired replica count through maxSurge. Kubernetes defaults rolling updates to 25% maxSurge, which means extra pods can exist during rollout.</p><p>So this is the number that matters: total_possible_connections = max_possible_pods x maximumPoolSize_per_pod</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*4sZd-x70UktX8iIW.png" /></figure><h3>3. Start from the database, not from Java</h3><p>The better question to ask is: <strong>How many database connections can a service safely consume across all pods?</strong> Rather than asking how many connections my Java app should have?</p><p>The rule is to always start with the database’s connection budget</p><p>As we know max_connections is the maximum number of concurrent connections to the server. Increasing it also increases server resources, so it should not be treated as a free knob. Databases like PostgreSQL also have reserved connection slots such as superuser_reserved_connections, which exist so administrators can still connect during emergencies.</p><p>A practical service-level budget looks like this:</p><p>usable_database_connections_for_a_service = database_max_connections minus a handful of reserved connections for things like:</p><ul><li>reserved_admin_connections</li><li>other_services_connections</li><li>migration_connections</li><li>batch_job_connections</li><li>observability_and_tooling_connections</li><li>safety_margin</li></ul><p>Example:</p><pre>Database max_connections: 300 <br>Admin/emergency reserve: 20 <br>Other microservices: 60 <br>Batch jobs and migrations: 15 <br>Monitoring and tooling: 5 <br>Safety margin: 40 <br><br>Usable for this service: 160</pre><p>That means this service should stay within roughly 160 database connections across all its pods.</p><p>The safety margin is not optional in Kubernetes. Pods can surge during rollouts. Pods can remain terminating. A canary can overlap with the main deployment. A retry storm can coincide with an autoscaling event. A database budget with no margin is a production incident waiting for a traffic spike.</p><blockquote><em>Also, </em><em>max_connections itself should generally not be increased aggressively because every backend process/session consumes memory even when idle.</em></blockquote><h3>4. Calculate the maximum possible pod count</h3><p>Now calculate the maximum realistic pod count:</p><pre>max_possible_pods = HPA_maxReplicas + <br>rollout_maxSurge_pods + <br>canary_overlap_pods + <br>job_or_worker_pods_that_use_the_same_pool_settings + <br>termination_overlap_buffer</pre><p>Example:</p><pre>HPA maxReplicas: 20 <br>Deployment maxSurge 25%: 5 <br>Canary pods: 2 <br>Termination overlap buffer: 1 <br><br>Max possible pods: 28</pre><p>Now divide the database budget by the max possible pods: per_pod_database_cap = floor(usable_database_connections_for_this_service / max_possible_pods)</p><p>Using the example:</p><pre>floor(160 / 28) = 5</pre><p>So the database-budget-based upper bound is: maximum-pool-size: 5</p><p>If someone sets it to 20 because “20 seems normal”, the real maximum becomes: 28 pods x 20 connections = 560 database connections</p><p>That is more than the entire database limit in this example. This is why pool sizing in Kubernetes must be done from the database backward.</p><h3>5. Estimate how many connections the app actually needs</h3><p>The database budget tells you the maximum safe cap. Now estimate application demand.</p><p>Use <a href="https://en.wikipedia.org/wiki/Little%27s_law">Little’s Law</a>: concurrent_database_connections_needed_per_pod ~= RPS_per_pod x DB_connection_hold_time_seconds</p><p>The important measurement here is not total HTTP request latency. It is the time the request holds a database connection.</p><p>For example:</p><ul><li><strong>Peak RPS per pod</strong>: 80 requests/second</li><li><strong>Average DB connection hold time</strong>: 50 ms (0.050 seconds)</li><li><strong>Concurrent DB need</strong>: 80 × 0.050 = 4</li></ul><p>That means the pod needs about 4 active database connections on average during that peak.</p><p>But you should not run a pool at 100% utilization all the time. Add headroom. A common target is around 70–80% utilization: pool_size_from_demand = ceil(concurrent_DB_need / target_utilization)</p><p>Using 75%:</p><pre>ceil(4 / 0.75) = 6</pre><p>So the application-demand estimate says: maximum-pool-size: 6</p><p>Now compare the two constraints:</p><ul><li><strong>Database-budget cap</strong>: 5</li><li><strong>Application-demand need</strong>: 6</li></ul><p>The safe starting point is 5, but this also tells you something important: the application wants more concurrent database work than the database budget can safely provide.</p><p>Now that is not a pool tuning problem. That is a capacity or efficiency problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*edPDoeohuB4umN-X.png" /></figure><h3>6. What if demand is greater than the database budget?</h3><p>Suppose the math says:</p><pre>Safe database cap per pod: 5 <br>Application demand per pod: 12</pre><p>Do not blindly set the pool to 12.</p><p>That would protect one pod’s latency for a short time by pushing the bottleneck into the database. Under real traffic, the database will become the shared failure point for every service using it.</p><p>Instead, reduce connection demand or increase database capacity.</p><p>Ways to reduce demand:</p><ul><li>Optimize slow queries.</li><li>Add required indexes.</li><li>Reduce transaction duration.</li><li>Avoid holding a DB connection while calling another service.</li><li>Reduce repeated queries inside loops.</li><li>Batch writes where safe.</li><li>Cache hot read paths.</li><li>Use read replicas for suitable read-heavy workloads.</li></ul><p>There are ways to increase capacity, but they will come at a cost 💸💸:</p><ul><li>Increase database CPU/memory/I/O capacity.</li><li>Separate workloads into different databases or clusters.</li></ul><h3>7. Understand maximumPoolSize</h3><p>In HikariCP, maximumPoolSize is the maximum number of connections in the pool, including idle and in-use connections. When the pool reaches that size and no idle connection is available, callers to getConnection() wait up to connectionTimeout before failing.</p><p>So this: maximum-pool-size: 8 means that this pod may hold at most 8 database connections. It does not mean that this service may hold at most 8 database connections.</p><p>In Kubernetes, always mentally expand it: maximumPoolSize_per_pod x max_possible_pods</p><p>A good starting range for many synchronous Java services is: 4 to 10 connections per pod</p><p>That sounds small, but <strong>many services spend most of their request time doing CPU work, serialization, cache calls, network calls, or waiting on downstream services</strong>. The database connection is usually held for a smaller slice of the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*qVODfP3T2YaqUtVd.png" /></figure><h3>8. Understand minimumIdle</h3><p>minimumIdle is the number of idle connections HikariCP tries to keep ready in the pool.</p><p>There are two common modes.</p><h3>Mode A: fixed-size pool</h3><pre>maximum-pool-size: 8 <br>minimum-idle: 8</pre><p>or simply omit minimumIdle, because HikariCP defaults it to the same value as maximumPoolSize.</p><p>A fixed pool keeps all connections warm. This is good when:</p><ul><li>Traffic is steady.</li><li>Latency matters more than conserving idle DB connections.</li><li>Connection creation is expensive.</li><li>Pod count is predictable.</li><li>The database can afford the idle sessions.</li></ul><p>The downside is that idle pods still hold database connections.</p><p>Example: 50 pods x minimumIdle 8 = 400 idle database connections</p><p>That can hurt the database even when traffic is low.</p><h3>Mode B: elastic pool</h3><pre>maximum-pool-size: 8 <br>minimum-idle: 2 <br>idle-timeout: 180000</pre><p>An elastic pool keeps a small warm baseline and grows under demand. After traffic drops, surplus idle connections above minimumIdle can be retired after idleTimeout.</p><p>This is good when:</p><ul><li>Traffic is spiky.</li><li>HPA can create many pods.</li><li>Many services share one database.</li><li>Idle connections are causing pressure.</li><li>You prefer slower cold bursts over high idle connection count.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sT44TDpiab0Y-icQ.png" /></figure><blockquote><em>HikariCP recommends leaving minimumIdle unset unless you have a specific reason to maintain an elastic pool.</em></blockquote><h3>9. Understand idleTimeout</h3><p>idleTimeout controls how long an unused connection may sit idle in the pool before HikariCP retires it.</p><p>But there is one critical rule: idleTimeout only matters when <strong>minimumIdle &lt; maximumPoolSize</strong></p><p>If you configure:</p><pre>maximum-pool-size: 8 <br>minimum-idle: 8 <br>idle-timeout: 60000</pre><p>then idleTimeout will not shrink the pool below 8. The pool is effectively fixed-size.</p><p>If you configure:</p><pre>maximum-pool-size: 8 <br>minimum-idle: 2 <br>idle-timeout: 60000</pre><p>then HikariCP can retire idle connections above 2 after they have been idle long enough.</p><p>If the timeout is too low, the application may repeatedly open and close connections, causing connection churn.</p><p>Connection churn can show up as:</p><ul><li>More frequent authentication work.</li><li>More TLS handshakes.</li><li>More database backend process/session churn.</li><li>Higher latency after quiet periods.</li><li>More logs that look like intermittent connection noise.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fn1vFXLTWUwdaSl0.png" /></figure><h3>10. Metrics to watch</h3><p>Spring Boot can instrument available DataSource objects and expose metrics for active, idle, maximum, and minimum connections. Exact metric names vary by Spring Boot and Micrometer version, but the concepts are the same.</p><p><strong>At the pool level, track</strong>:</p><ul><li>active connections</li><li>idle connections</li><li>max connections</li><li>min connections</li><li>pending/waiting threads</li><li>connection acquisition time</li><li>connection timeout errors</li><li>connection creation rate</li></ul><p><strong>At the application level, track</strong>:</p><ul><li>RPS per pod</li><li>p95/p99 HTTP latency</li><li>request error rate</li><li>request thread utilization</li><li>retry rate</li></ul><p><strong>At the database level, track</strong>:</p><ul><li>total connections</li><li>active sessions</li><li>idle sessions</li><li>CPU utilization</li><li>I/O wait</li><li>lock waits</li><li>slow queries</li><li>deadlocks</li><li>transaction duration</li><li>replication lag, if applicable</li></ul><h3>Pool too small</h3><ul><li>Pending connection requests are frequently above zero.</li><li>Connection acquisition latency rises.</li><li>Hikari connection timeout exceptions occur.</li><li>Database still has spare CPU and low active-session pressure.</li></ul><h3>Pool too large</h3><ul><li>Database CPU is high.</li><li>Lock waits increase.</li><li>Query latency increases.</li><li>More connections are active but throughput does not improve.</li><li>App latency gets worse after increasing pool size.</li></ul><h3>11. Common anti-patterns</h3><h3>Anti-pattern 1: pool size equals web thread count</h3><p>Bad:</p><pre>Tomcat max threads = 200 <br>Hikari maximumPoolSize = 200</pre><p>That allows every request thread to hit the database at the same time. Most databases cannot efficiently execute that much concurrent work for one service.</p><p>Better:</p><pre>Tomcat max threads = 200 <br>Hikari maximumPoolSize = based on DB budget and measured DB hold time</pre><h3>Anti-pattern 2: sizing from current pods instead of max pods</h3><p>Bad:</p><pre>Current pods = 4 <br>maximumPoolSize = 20 <br>Total today = 80 connections</pre><p>But the real environment might be:</p><pre>HPA maxReplicas = 30 <br>Deployment maxSurge = 25% <br>Possible pods ~= 38 <br><br>38 x 20 = 760 possible connections</pre><p>The database sees the worst case, not your screenshot from a quiet afternoon.</p><h3>Anti-pattern 3: high minimumIdle everywhere</h3><p>Bad:</p><pre>maximum-pool-size: 20 <br>minimum-idle: 20</pre><p>on many services.</p><p>This creates many idle database sessions. Idle does not mean free. Idle connections still consume database memory, connection slots, and operational headroom.</p><h3>Anti-pattern 4: increasing the pool when queries are slow</h3><p>If queries are slow because of missing indexes, lock waits, I/O saturation, or bad query plans, a larger pool usually makes the pileup worse.</p><p>Fix query time first.</p><h3>Anti-pattern 5: holding a connection during remote calls</h3><p>Bad:</p><pre>open transaction <br>write row <br>call payment service <br>call inventory service <br>commit transaction</pre><p>The database connection stays open while the application waits on the network.</p><p>Better where possible:</p><pre>call external services <br>open transaction <br>do short DB work <br>commit</pre><p>Shorter connection hold time reduces the pool size needed for the same RPS</p><h3>12. Production checklist</h3><p>Before choosing the final values, ask these questions:</p><ol><li>If every pod opens a maximumPoolSize number of connections, will the database survive?</li><li>If every pod keeps minimumIdle connections, will the database have too many idle sessions?</li><li>If the pool is exhausted, will the app fail fast or block long enough to cascade?</li><li>Is maxLifetime lower than any database/proxy/network connection lifetime?</li><li>Are we holding connections during external service calls?</li><li>Do load tests show throughput improvement when the pool increases?</li><li>Do database metrics stay healthy at the chosen size?</li></ol><h3>13. Final mental model</h3><p>Use this picture whenever you configure database connections for Java in Kubernetes:</p><ul><li>Database capacity is global.</li><li>Pods are multiplied.</li><li>Pools are per pod.</li><li>maximumPoolSize is a per-pod bulkhead.</li><li>minimumIdle is the idle connection cost per pod.</li><li>idleTimeout Only releases connections above minimumIdle.</li><li>The best pool is usually the smallest pool that avoids unnecessary connection wait.</li></ul><p>The most dangerous setting is not always a high maximumPoolSize. Sometimes it is a high minimumIdle across many pods.</p><p>The best configuration is not the one that makes one pod look fast in isolation. It is the one that keeps the whole system stable when Kubernetes scales, deploys, retries, and recovers.</p><p>In microservices, connection pooling is not just an application performance setting.</p><p>It is database capacity management.</p><h3>References</h3><ul><li><a href="https://github.com/brettwooldridge/HikariCP">HikariCP Configuration</a></li><li><a href="https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing">HikariCP About Pool Sizing</a></li><li><a href="https://kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/">Kubernetes Horizontal Pod Autoscaling</a></li><li><a href="https://www.postgresql.org/docs/current/runtime-config-connection.html">PostgreSQL Connections and Authentication</a></li></ul><p><em>Originally published at </em><a href="https://apoorvtyagi.tech/how-to-size-java-database-connection-pools-in-kubernetes"><em>https://apoorvtyagi.tech</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d95d778693d6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-size-java-database-connection-pools-in-kubernetes-d95d778693d6">How to Size Java Database Connection Pools in Kubernetes</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Jib? A Complete Guide to Java Containerization Without Dockerfiles]]></title>
            <link>https://levelup.gitconnected.com/what-is-jib-a-complete-guide-to-java-containerization-without-dockerfiles-1edf5f4970aa?source=rss-f4730edde1e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1edf5f4970aa</guid>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Apoorv Tyagi]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 14:34:09 GMT</pubDate>
            <atom:updated>2026-03-13T14:30:20.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="What’s Jib?" src="https://cdn-images-1.medium.com/max/1024/1*X7BplkXJgYWNsv9mpKz8qw.png" /></figure><p>When I joined PayPay, one of the first things I tried to understand was how our services were containerized.</p><p>A common exercise when joining a new backend team is to look at the Dockerfiles used across services as they often reveal interesting patterns:</p><p>So naturally, I went looking for the Dockerfile.</p><p>But to my surprise… I couldn’t find one.</p><p>After digging a bit deeper, I realized something interesting. The project wasn’t using a Dockerfile at all<strong>.</strong> Instead, it was using <a href="https://github.com/GoogleContainerTools/jib">Jib</a>.</p><h3>📦 Enter Jib</h3><p>Imagine shipping a Java microservice where changing a single line of code doesn’t force your CI pipeline to rebuild a massive container image.</p><p>That’s exactly what Jib enables.</p><p>Jib is an open-source container image builder for Java applications that:</p><ul><li><strong>Eliminates the need for a Dockerfile</strong></li><li><strong>Does not require a Docker daemon</strong></li><li><strong>Integrates directly with Maven and Gradle</strong></li></ul><p>Instead of packaging your application as a single fat layer, Jib understands Java project structure and splits your application into optimized layers:</p><ul><li>Runtime (base image)</li><li>Dependencies</li><li>Resources</li><li>Application classes</li></ul><p>Because of this layered structure, when you change only your application code, only the top layer is rebuilt and pushed.</p><p>The result?</p><ul><li>⚡ Faster builds</li><li>🧱 Better caching</li><li>🚀 Simpler CI pipelines</li><li>🔧 Less Dockerfile maintenance</li></ul><p>In this post, we’ll explore how Jib works, when to use it, and how it compares to traditional Dockerfiles.</p><h3>🚀 What’s Jib?</h3><p>If you build Java applications and ship containers, you’ve probably written Dockerfiles like this:</p><pre>FROM eclipse-temurin:17-jre<br>WORKDIR /app<br>COPY target/app.jar app.jar<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>It works.</p><p>But it’s not optimized for Java.</p><p>This is where Jib changes the game.</p><h3>🧱 The Problem With Traditional Docker Builds</h3><p>Before Jib, containerizing Java apps required:</p><ul><li>Writing and maintaining Dockerfiles</li><li>Installing Docker everywhere (including CI)</li><li>Packaging fat JARs</li><li>Rebuilding full images for small code changes</li><li>Manually optimizing layers</li></ul><p>Even a small code change could invalidate caching and rebuild everything.</p><p>That’s inefficient.</p><h3>🧠 How Jib Works</h3><p>Jib builds container images by splitting your app into logical layers:</p><ol><li>Base Image (JRE)</li><li>Dependencies</li><li>Resources</li><li>Application classes</li></ol><p>This means:</p><ul><li>If dependencies don’t change → layer reused</li><li>If only code changes → only top layer rebuilt</li></ul><p>This drastically improves CI speed.</p><h3>🛠️ Getting Started with Jib</h3><h3>Maven Setup</h3><p>Add this to your pom.xml:</p><pre>&lt;plugin&gt;<br>  &lt;groupId&gt;com.google.cloud.tools&lt;/groupId&gt;<br>  &lt;artifactId&gt;jib-maven-plugin&lt;/artifactId&gt;<br>  &lt;version&gt;3.4.0&lt;/version&gt;<br>  &lt;configuration&gt;<br>    &lt;to&gt;<br>      &lt;image&gt;ghcr.io/yourorg/yourapp&lt;/image&gt;<br>    &lt;/to&gt;<br>  &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><p>Build &amp; push:</p><pre>mvn compile jib:build</pre><h3>Gradle Setup</h3><pre>plugins {<br>  id(&quot;com.google.cloud.tools.jib&quot;) version &quot;3.4.0&quot;<br>}<br><br>jib {<br>  to {<br>    image = &quot;ghcr.io/yourorg/yourapp&quot;<br>  }<br>}</pre><p>Build:</p><pre>./gradlew jib</pre><h3>⚔️ Dockerfile vs Jib — Which Is Better?</h3><p>This is the real question.</p><p>The answer depends on some of the use cases.</p><h3>✅ When Jib Is Better</h3><h4>1. Standard Java Microservices</h4><ul><li>Spring Boot</li><li>Micronaut</li><li>Quarkus</li><li>Plain Maven/Gradle apps</li></ul><p>Jib integrates directly with your build system.</p><h4>2. Faster CI/CD Pipelines</h4><p>Jib:</p><ul><li>Does not require a Docker daemon</li><li>Builds incremental layers</li><li>Pushes smaller diffs</li><li>Produces reproducible builds</li></ul><p>If CI time matters, Jib usually wins.</p><h4>3. Developer Simplicity</h4><p>No Dockerfile. No manual layering. Less DevOps friction.</p><h3>🏗️ When Dockerfile Is Better</h3><h4>1. OS-Level Customization</h4><p>If you need:</p><ul><li>apt-get install</li><li>Native libraries</li><li>Custom shell scripts</li></ul><p>Jib does not support arbitrary RUN commands.</p><p>Dockerfile wins here.</p><h4>2. Polyglot Applications</h4><p>If your container includes:</p><ul><li>Node + Java</li><li>Python + Java</li><li>Multiple build tools</li><li>Custom entrypoints</li></ul><p>Dockerfile provides full flexibility.</p><h4>3. Complex Multi-Stage Builds</h4><p>Example:</p><ul><li>Compile native binaries</li><li>Build frontend assets</li><li>Run security scans during build</li><li>Copy artifacts between stages</li></ul><p>Dockerfile is more powerful here.</p><h3>📊 Side-by-Side Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*ylc-OU3s-Q9-rAcJ7oD4qw.png" /><figcaption>Jib v.s. dockerfile</figcaption></figure><h3>🎯 Real-World Scenarios</h3><h3>Scenario A: 20 Spring Boot Microservices</h3><ul><li>Kubernetes</li><li>GitHub Actions</li><li>CI cost matters</li></ul><p>👉 Jib is usually the better choice.</p><h3>Scenario B: Enterprise App With Native Dependencies</h3><ul><li>Custom Alpine base image</li><li>OS packages</li><li>Hardening scripts</li><li>Multi-stage builds</li></ul><p>👉 Dockerfile is better.</p><h3>Scenario C: Small Startup Team</h3><ul><li>Java-only stack</li><li>No DevOps team</li><li>Want fast pipelines</li></ul><p>👉 Jib simplifies everything.</p><h3>🔬 Performance Insight</h3><p>Because Jib separates dependencies and classes:</p><ul><li>Code-only changes rebuild in seconds</li><li>Docker layer cache invalidation is minimized</li><li>CI builds are more predictable</li></ul><p>In large microservice ecosystems, this adds up significantly.</p><h3>🚀 Closing Thoughts</h3><p>Jib is optimized for:</p><blockquote><em>Java developer productivity.</em></blockquote><p>Dockerfile is optimized for:</p><blockquote><em>Infrastructure control.</em></blockquote><p>If you build modern Java microservices → Start with Jib.</p><p>If you need deep OS-level control → Use Dockerfile.</p><p>Containerization doesn’t have to be complicated. If your stack is Java-centric and you value speed, reproducibility, and developer autonomy, then Jib is one of the smart tools you can adopt today.</p><p><em>Originally published at </em><a href="https://apoorvtyagi.tech/what-is-jib-a-complete-guide-to-java-containerization-without-dockerfiles"><em>https://</em>apoorvtyagi.tech</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1edf5f4970aa" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/what-is-jib-a-complete-guide-to-java-containerization-without-dockerfiles-1edf5f4970aa">What is Jib? A Complete Guide to Java Containerization Without Dockerfiles</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Consumer Container Restarts in Kubernetes: A Production Case Study]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/kafka-consumer-container-restarts-in-kubernetes-a-production-case-study-8703203e5fa7?source=rss-f4730edde1e1------2"><img src="https://cdn-images-1.medium.com/max/1536/1*KmXul9e6LcieNy-Q24bydQ.png" width="1536"></a></p><p class="medium-feed-snippet">Background</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/kafka-consumer-container-restarts-in-kubernetes-a-production-case-study-8703203e5fa7?source=rss-f4730edde1e1------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/kafka-consumer-container-restarts-in-kubernetes-a-production-case-study-8703203e5fa7?source=rss-f4730edde1e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8703203e5fa7</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Apoorv Tyagi]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 11:20:09 GMT</pubDate>
            <atom:updated>2026-03-02T15:24:08.513Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How we solved cache invalidation in Kubernetes with a headless service]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/how-we-solved-cache-invalidation-in-kubernetes-with-a-headless-service-14661e2c92bb?source=rss-f4730edde1e1------2"><img src="https://cdn-images-1.medium.com/max/1424/1*zimHGmS2eTW46ZNWrUY1iA.png" width="1424"></a></p><p class="medium-feed-snippet">The $0 solution to a Distributed Cache Invalidation</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/how-we-solved-cache-invalidation-in-kubernetes-with-a-headless-service-14661e2c92bb?source=rss-f4730edde1e1------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/how-we-solved-cache-invalidation-in-kubernetes-with-a-headless-service-14661e2c92bb?source=rss-f4730edde1e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/14661e2c92bb</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Apoorv Tyagi]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 19:09:53 GMT</pubDate>
            <atom:updated>2026-01-11T19:09:57.852Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Going Vernacular: Engineering Our Way to Process Multilingual Names]]></title>
            <link>https://javascript.plainenglish.io/going-vernacular-engineering-our-way-to-process-multilingual-names-a21d6daac591?source=rss-f4730edde1e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21d6daac591</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Apoorv Tyagi]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 17:03:51 GMT</pubDate>
            <atom:updated>2024-07-24T06:16:46.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5_WBwQFCfUobi6wAFHVSw.png" /></figure><p>At our current organization, earlier this year as we were looking at the errors at one of our signup APIs, we observed that nearly 5% of our requests were getting failed, all due to <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400">400 BAD REQUEST</a> errors, and the root cause was traced back to a regex check.</p><p>This regex was a constraint in that our system allowed users to input their first and last names only in English characters. Yet, many individuals opted to enter their names in their native languages. Particularly, these customers were the people who were interested in purchasing health policies from our platform hence making them a crucial segment of our user base.</p><p>In response to this, we decided to address the 5% case by enabling users to enter their names in any language they preferred. However, this brings up a lot of challenges that we need to solve.</p><h3>Challenges with Processing Multilingual Names</h3><h3>1. Data Storage Strategy</h3><p>We rely on MongoDB for storage and retrieval of user names. While MongoDB allows storage for all UTF-8 compatible characters, the problem comes when dealing with search. For English names, our search operations utilize the <a href="https://www.mongodb.com/docs/manual/reference/collation/">simple collation</a> method. The corresponding fields are appropriately indexed to optimize query performance.</p><p>While the option to implement a <a href="https://www.mongodb.com/docs/manual/reference/collation/">collation index</a> for other languages also exists in MongoDB, this approach necessitates informing DB about the specific language for which we intend to search. The challenge here is that our user base spans many languages, with India alone having more than 20 diverse languages.</p><p>Since our objective was to extend support to at least all Indian languages, implementing collation indexes for every supported language would lead to an increased number of indexes and hence an increase in index size over time as well.</p><p>Additionally, this approach would place the responsibility on developers to remember to add an index for each new language as our language support expands, which is far from an efficient solution.</p><h3>2. API Gateway Constraint</h3><p>All our APIs are exposed behind an API gateway and just before the gateway forwards a request to the respective API service, an inbound policy verifies the user’s authentication status. Once the user is authenticated, it retrieves basic user details such as name, mobile number, and other metadata, and appends it to a request header of that API.</p><p>A multitude of APIs rely on this user-specific data in headers for their further processing.</p><p>However, there’s a restriction imposed by the gateway — it allows only <a href="https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html">ASCII</a> characters for processing and inclusion in the headers. So we had to make sure even though the name is in any other language, the response we share must be exclusively in English.</p><p>Also, this process must remain fast, as any delay in authentication could lead to sluggish API performance.</p><h3>3. External Partners’ Challenge with Vernacular Names</h3><p>Even if we started to accept names in multiple languages, there were our partners who had to accept those names from us. If they don’t support multilingual names, the user journey breaks. One such was our payment partner. We had to make sure our payments team always received the English name even when users provided names in other languages.</p><p>Also, we wanted to avoid those annoying pop-ups prompting users to enter their names in English whenever we needed to. So keeping these problems in mind we had to build a viable solution.How We Solved These Challenges</p><p>While utilizing a third-party transliteration service might have been the easiest route, we opted to develop an in-house solution to control costs and maintain full control.</p><p>Considering the API gateway and the requirements of payment partners, it became clear that we needed to transform non-English names into English equivalents. But presenting this English name to the user was counterintuitive — for example entering a name in Hindi, only to see it transformed into English upon logging in seemed contradictory.</p><p>To handle this, we developed a dual-naming strategy. The original fields, &quot;firstName&quot; and &quot;lastName&quot; would retain the user-entered names in their entered language. Then we introduced two additional fields, &quot;englishFirstName&quot; and &quot;englishLastName&quot; that were dedicated to storing the English counterparts of these names. These English names could then be shared with the API gateway and our payment partners.</p><p>Coming back to the challenge of storing these names efficiently, we anticipated that managing collation indexes as the number of supported languages grew would become unmanageable. Searching would also require specifying the collation for each query, creating an added layer of complexity. So we decided to pivot away from this approach.</p><p>Our second approach involved using Unicode. As we aimed to support multiple languages without constraints, we recognized that Unicode could effectively represent characters in nearly every language. Because of this, we decided to store Unicode representations for first and last names in their respective MongoDB fields.</p><p>We just added another layer between our DB and the application. It converts these Unicode strings to the original values in the local language while retrieving the names from the DB and converting the local names to their respective English names. Then it stores them in englishFirstName and englishLastName at the time of any insert or update.</p><p>This strategy provided the flexibility we needed to manage multilingual names seamlessly.</p><h3>Solutioning</h3><p>While utilizing a third-party transliteration service might have been the easiest route, we opted to develop an in-house solution to control costs and maintain full control.</p><p>Considering the API gateway and the requirements of payment partners, it became clear that we needed to transform non-English names into English equivalents. However, presenting this English name to the user was counterintuitive — for example entering a name in Hindi, only to see it transformed into English upon logging in seemed contradictory.</p><p>Therefore, we developed a dual-naming strategy. The original fields, &quot;firstName&quot; and &quot;lastName&quot; would retain the user-entered names in their entered language, while we introduced two additional fields, &quot;englishFirstName&quot; and &quot;englishLastName&quot; dedicated to storing the English counterparts of these names. These English names could then be shared with the API gateway and our payment partners.</p><p>Coming back to the challenge of storing these names efficiently, we anticipated that managing collation indexes as the number of supported languages grew would become unmanageable. Additionally, searching would require specifying the collation for each query, creating an added layer of complexity. Hence, we decided to pivot away from this approach.</p><p>Our second approach involved using Unicode. As we aimed to support multiple languages without constraint, we recognized that Unicode could effectively represent characters in nearly every language. Consequently, we decided to store Unicode representations for first and last names in their respective MongoDB fields.</p><p>We just added another layer between our DB and the application that converts these Unicode strings to the original values in the local language while retrieving the names from DB and converting the local names to their respective English names for storing them in englishFirstName and englishLastName at the time of any insert or update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*UkXinqWmcflDwBbD" /></figure><p>This strategy provided the flexibility we needed to manage multilingual names seamlessly.</p><h3>Key Design Considerations</h3><h4>1. Unicode Optimization</h4><p>Unicode representation typically comprises a 6-character string, with ‘a’ represented as ‘U+0061’ and ‘P’ as ‘U+0050,’ commonly commencing with ‘U+00.’ To conserve space in our database storage, we opted to omit the ‘U+’ prefix and leading zeros, optimizing our data storage.</p><h4>2. Transliteration vs. Translation</h4><p>Initially, our aim was transliteration, which requires converting names from one script to another while retaining their phonetic sound.</p><p>For example, the Hindi word &quot;प्रतीक्षा&quot; should be transformed to &quot;Partiksha&quot; and not translated to its English equivalent, &quot;Wait&quot;.</p><p>However, we recognized that Google Translate primarily focuses on translation, not transliteration. Again we didn’t want to go directly for the paid Google transliteration service in our first iteration, so we developed our transliteration service using the free version of Google Translate.</p><h4>3. Contextual Enhancements</h4><p>Another and the most crucial observation that we had was providing context to the Google Translate API that influenced its responses.</p><p>To leverage this, we experimented with adding statement prefixes to non-English names to establish context. After a few hits and trials, we realized that for shorter names (less than 5 characters), a more extensive prefix statement didn’t yield desirable results, and Google often returned the same Hindi word. For longer names, we employed lengthier statements, determining the optimal balance through trial and error.</p><p>Translating names normally led to their literal translation. For example “प्रतीक्षा” to “Wait” instead of “Pratiksha”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*SACqCsOHcTtkUy3Y" /></figure><p>Adding a prefix statement corrected it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*U9dIhlnZPPERylYi" /></figure><p>Alright, now let’s see how we implemented all this.</p><h3>Initial Code</h3><p>After our first iteration, we developed the below code for transliteration. Here we are using the @iamtraction/google-translate library which is a wrapper written over the free Google translate API.</p><pre>const translate = require(&#39;@iamtraction/google-translate&#39;);<br><br>function getGoogleTranslateText(localName) {<br>  /*<br>    Adding an English sentence before the name so that<br>    it doesn&#39;t get translated to its literal meaning.<br>    For eg परीक्षा to Exam instead of Pariksha.<br>  */<br>  if (localName.length &lt;= 5) {<br>    return `name: ${localName}`;<br>  }<br>  return `your name is: ${localName}`;<br>}<br><br>async function translateNameToEnglish(localName) {<br>  if (localName.match(/^[a-zA-Z ]+$/i)) {<br>    // If the name is already in English just return<br>    return localName;<br>  }<br>  try {<br>    const res = await translate(getGoogleTranslateText(localName), {<br>      to: &#39;en&#39;,<br>    });<br>    const translatedName = res.text.split(&#39;:&#39;)[1].trim();<br>    return translatedName;<br>  } catch (err) {}<br>  // In case of error, Return the Unicode string<br>  return localName;<br>}</pre><h3>Beta Release and Production Challenges</h3><p>Once we built this, we released the feature in beta, and approximately 250 users signed up with non-English names within the first few days.</p><p>Upon simple eyeballing on translated texts, we found out that the process of converting the name from its local language to Unicode was working perfectly fine and users were able to view their names properly in the application in the language they preferred but we identified two issues as far as the process of transliteration to English was concerned:</p><ol><li><strong>Some names were incorrectly transliterated.</strong> This occurrence could be attributed to our dependence on Google Translate, a general translation service, rather than a specialized transliteration service.</li><li><strong>Some names remained unaltered and were not transliterated.</strong> These names were returned in the same language as the original one. This meant adding context with prefix sentences before the translation was causing problems for specific names.</li></ol><p>This prompted a further investigation that led us to another npm package called “unidecode,” which converts Unicode to the original string. While initial tests with unidecode showed accuracy, they also revealed minor spelling discrepancies. In contrast, Google consistently delivered translations with correct spellings. We just needed to find a way of using the best of both worlds.</p><p>Hence, we incorporated unidecode into our algorithm as part of our solution.</p><h3>Improved Solution</h3><p>Here’s what we came up with:</p><pre>const translate = require(&#39;@iamtraction/google-translate&#39;);<br>const unidecode = require(&#39;unidecode&#39;);<br>const { isAlmostEqualStrings } = require(&#39;./levenshtein&#39;);<br>/**<br> *<br> * @param {String} localName<br> * @description Generates text for Google (shorter statement context for short names) based on localName length<br> * @returns {String} returns text to translate<br> */<br>function getGoogleTranslateText(localName) {<br>  /*<br>    Adding an English sentence before name so that<br>    it doesn&#39;t get translated to its literal meaning.<br>    For eg परीक्षा to Exam instead of Pariksha.<br>  */<br>  if (localName.length &lt;= 5) {<br>    return `name: ${localName}`;<br>  }<br>  return `your name is: ${localName}`;<br>}<br><br>/**<br> *<br> * @param {String} localName<br> * @description Give an ALMOST transliterated name<br> * @returns {String} returns a converted transliterated name from the local language<br> */<br>function transliterate(localName, googleTranslatedName) {<br>  const decodedName = unidecode(localName);<br>  if (<br>    decodedName &amp;&amp;<br>    Array.from(decodedName)[0]?.toLowerCase() !==<br>      Array.from(googleTranslatedName)[0]?.toLowerCase() &amp;&amp;<br>    !isAlmostEqualStrings(decodedName, googleTranslatedName)<br>  ) {<br>    return decodedName;<br>  }<br>  return googleTranslatedName;<br>}<br><br>/**<br> *<br> * @param {String} Input non English string<br> * @description translates non-english string to English<br> * @returns {String} returns translated string<br> */<br>async function translateNameToEnglish(localName) {<br>  if (!localName || localName.match(/^[a-zA-Z ]+$/i)) {<br>    // If name is already in English just return<br>    return localName;<br>  }<br>  try {<br>    const res = await translate(getGoogleTranslateText(localName), {<br>      to: &#39;en&#39;,<br>    });<br>    const translatedName = res.text.split(&#39;:&#39;)[1].trim();<br>    return transliterate(localName, translatedName);<br>  } catch (err) {}<br>  // In case of error, Return original string<br>  return localName;<br>}</pre><p>After obtaining the translated name, we feed it into the recently introduced transliterate function. Inside this function, our initial step involves extracting the decoded string using the Unidecode library. But then the crux of the matter arises: wow do we determine which result to prioritize - the decoded string or the translated string?</p><p>To tackle this, we implemented <a href="https://en.wikipedia.org/wiki/Levenshtein_distance"><strong>Levenshtein Distance</strong></a>, an algorithm that calculates the similarity between two strings.</p><p>Initially, we check if the first character of the decoded name matches the first character of the translated name. If it doesn’t match, then for sure the translated name was incorrect, so we return the decoded name, even though it might contain minor spelling discrepancies, it’s better to use that than the incorrect translation.</p><p>If it does match then we go for the Levenshtein Distance algorithm.</p><blockquote><em>The Levenshtein distance is a number that tells you how similar two strings are. The higher the number, the more dissimilar the two strings are.</em></blockquote><p>In the implementation, we have a function isAlmostEqualStrings that generates a value from 0 to 1 and returns true if the value is above a certain threshold. In our case, we set the threshold to 0.8</p><p>If the Levenshtein distance indicates a match exceeding 80%, we return the translated name. Otherwise, we return the decoded name. This approach ensures that we prioritize accuracy, offering a reliable result based on the established similarity threshold.</p><p>This updated algorithm substantially reduced the above mentioned issues. Even though it’s not 100% accurate, it solved our 5% cases very well.</p><h3>Conclusion</h3><p>The algorithm developed was entirely in-house and incurred no costs. While investing in a paid solution might have potentially offered better results, wise engineering decisions taken iteratively and a handful of clever hacks played a vital role in both reducing costs and efficiently resolving the specific problem we had.</p><p>The complete code for the above implementation along with the Levenshtein Distance algorithm can be found on <a href="https://github.com/ApoorvTyagi/english-transliterate"><strong>GitHub</strong></a> (contributions/corrections are welcome).</p><p>With this, we come to the end of the article. My DMs are always open if you want to discuss further on any tech topic or if you’ve got any questions, suggestions, or feedback in general:</p><ul><li><a href="https://twitter.com/apoorv__tyagi">Twitter</a></li><li><a href="https://www.linkedin.com/in/apoorvtyagi/">LinkedIn</a></li><li><a href="https://github.com/apoorvtyagi">Github</a></li></ul><p>Happy learning!</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21d6daac591" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/going-vernacular-engineering-our-way-to-process-multilingual-names-a21d6daac591">Going Vernacular: Engineering Our Way to Process Multilingual Names</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</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 Choose the Right Database for Your Application]]></title>
            <link>https://javascript.plainenglish.io/how-to-choose-the-right-database-for-your-application-11475c9ff242?source=rss-f4730edde1e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/11475c9ff242</guid>
            <category><![CDATA[sql-vs-nosql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Apoorv Tyagi]]></dc:creator>
            <pubDate>Sun, 15 May 2022 12:03:09 GMT</pubDate>
            <atom:updated>2022-05-19T16:19:41.319Z</atom:updated>
            <content:encoded><![CDATA[<h4>The factors you should consider while choosing any database for your application.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHmSEGSZiHOwVf1plg-cow.png" /></figure><h3>Introduction</h3><p>Choosing which database to use is one of the most important decisions you can make when starting working on a new app or website.</p><p>If you realize down the line that you’ve made the wrong choice, migrating to another database is very costly and sometimes more complex to do with zero downtime.</p><p>Taking time to make an informed choice of database technology upfront can be a valuable early decision for your application.</p><p><em>(A bonus reason for why this is important is because understanding the different DBs and their properties &amp; which one to choose over the other is quite commonly asked in job interviews)</em></p><p>Each database technology has advantages and disadvantages. Cloud providers like Amazon offer various database and storage options making it harder to figure out which one is the right one.</p><p>Relational databases have been a primary data storage mechanism for a long time. Non-relational databases have existed since the 1960s but recently gained traction with popular options such as MongoDB.</p><p>In this article, we will go through the factors you should consider while choosing any database.</p><h3>The language determines the database</h3><p>First things first. The language or the technology you are going to use never determines the database ❌</p><p>We’ve grown accustomed to technology stacks, such as MERN (MongoDB, Express, React, Node.js) &amp; LAMP (Linux, Apache, MySQL, PHP).</p><p>There are certain reasons why these stacks evolved. But don’t assume these are the rules. You can use a MongoDB database in your Java project. You can use MySQL in your Node.js. You might not have found as many tutorials, but it’s your requirements that should determine the database type &amp; not the language.</p><h3>Understanding the Tradeoff</h3><p>Let’s now understand the basic tradeoffs we need to deal with while making the DB decision.</p><p>The reason that we have many database options available today is due to the CAP Theorem. CAP stands for <strong>Consistency</strong>, <strong>Availability</strong>, and<strong> Partition tolerance</strong>.</p><p><strong>Consistency </strong>means that any read request will return the most recent write.</p><p><strong>Availability </strong>means all (non-failing) nodes are available for queries &amp; must respond in a reasonable amount of time.</p><p><strong>Partition Tolerance</strong> means that the system will continue to work despite node failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*vQXz-w13wJ65w6ft" /></figure><p>Only two of these 3 requirements can be fulfilled at any given time. If you’re building a distributed app then partition tolerance is a must. So the choice remains whether we want our database to be highly available or highly consistent.</p><h3>Structure of Data</h3><p>If your data needs to be structured or there is a relation between different types of data that you’re going to keep and at the same time you want strict data integrity then a relational database should be a better choice for you.</p><p>For example, let’s say we are making a student management application where we need to store the information of certain courses and every course needs to be taken by one or more students. In this case, we can create 2 tables ( Students and Courses) where the value in the Student ID column inside the Courses table points to rows in the Students table by the value of their ID column.</p><p>Apart from this if you want your DB to be <a href="https://en.wikipedia.org/wiki/ACID">ACID</a> compliant for example in cases when you’re handling payments and transactions in your application then in that case too you should prefer the SQL-based databases because the counterpart i.e the NoSQL database offers weak consistency.</p><blockquote><em>ACID compliance protects the integrity of your data by defining exactly what a transaction is and how it interacts with your database. It avoids database tables from becoming out-of-sync, which is super important for financial transactions. ACID compliance guarantees the validity of transactions even in the face of errors, technology failures, disastrous events, and more.</em></blockquote><p>On the other hand, if your data requirements aren’t clear or if your data is unstructured, NoSQL may be your best choice.</p><p>The data you store in a NoSQL database does not need a predefined schema. This provides much more flexibility and less upfront planning when managing your database.</p><p>A NoSQL database is a much better fit to store data like article content, social media posts, sensor data, and other types of unstructured data that won’t fit neatly into a table. NoSQL databases were built with flexibility and scalability in mind and follow the BASE consistency model, which means:</p><h4>Basic Availability</h4><p>This means that while the database guarantees the availability of the data, the database may fail to obtain the requested data, or the data may be in a changing or inconsistent state.</p><h4>Soft state</h4><p>The state of the database can be changing over time.</p><h4>Eventual consistency</h4><p>The database will eventually become consistent, and data will propagate everywhere at some point in the future.</p><p>The structure of your data is the most important factor in deciding whether to use a SQL or NoSQL database, so put a lot of thought into this before making a decision.</p><h3>Query Patterns</h3><p>The next factor to consider is how you’ll query your data. This is one of the main ways to find the best database for your use case</p><p>Do you need retrieval by a single key, or by various other parameters? Do you also need a fuzzy search on the data?</p><ul><li>Use Non-Relational databases if you are going to fetch data by key, then all you need is a key-value store (e.g. DynamoDB).</li><li>On the other hand, if you will require to query many different fields you can choose both Relational DB (e.g.MySQL) or Document DB (e.g.MongoDB).</li><li>In case you are looking for fuzzy search query capabilities (free text search), then search engines like Elasticsearch(Which also comes under NoSQL DBs) are the best fit.</li><li>But in case your data is nicely structured and organized, it is very efficient to query your data with a SQL database.</li></ul><blockquote><em>SQL is a popular query language that has been around for over 50 years now, so it’s highly mature and well-known. It efficiently executes queries and retrieves using JOINs and edits data quickly. It’s very lightweight and declarative.</em></blockquote><h3>Consistency</h3><p>Is strong consistency required (read after write) or eventual consistency is OK?</p><p>In case you need to read your data right after your write operation (i.e. strong consistency) then a Relational database (e.g. MySQL) is usually more suited than a Non-Relational Database (e.g.MongoDB).</p><h3>Performance &amp; Scaling</h3><p>All databases’ performance degrades as the amount of read/write traffic increases. This is the time when optimizations such as indexing your data and scaling your DB come into the picture.</p><p>Performance depends on various factors but the overall performance depends to a very large degree on choosing the right implementation for your use case.</p><p>SQL and NoSQL databases scale differently, so you’ll have to think about how your data set will grow in the future.</p><p>SQL databases scale vertically, meaning you’ll need to increase the capacity of a single server (increasing CPU, RAM, or SSD) to scale your database. SQL databases were designed to maintain the integrity of the data so they are best to run on a single server, hence they’re not easy to scale.</p><p>NoSQL databases are easy to scale horizontally, which means you can add more servers as your data grows. This is an advantage that NoSQL has over SQL.</p><p>This uncomplicated horizontal scaling nature of non-relational databases makes them superior to relational databases as far as availability is concerned.</p><p>The ability of NoSQL databases to scale horizontally has to do with the lack of structure of the data. Because NoSQL requires much less structure than SQL, each stored object is pretty much self-contained. Thus objects can be easily stored on multiple servers without having to be linked. This is not the case for SQL, where each table row and column needs to be related.</p><p>This is also the issue regarding performance and where SQL falls short is scaling. As a database grows in size and numbers, RDBMS as we have seen requires solutions in vertical scaling. This however comes at a significant cost. Although many commercial RDBMS products offer horizontal scaling, these can also be very expensive and even complex to implement.</p><p>If you predict you will face such an issue, then NoSQL is to be considered, as many of them were designed specifically to tackle these scale and performance issues.</p><h3>Conclusion</h3><p>In this article, we went through the multiple factors you should consider while selecting the type of database. In short, SQL databases provide great benefits for transactional data whose structure doesn’t change frequently (or at all) and where data integrity is paramount. It’s also best for fast analytical queries. NoSQL databases provide more flexibility and scalability, which makes them useful for rapid or iteration development.</p><p>Here’s a small summary of what all we have discussed above:</p><h3>Reasons to use an SQL database</h3><ul><li>When you need ACID support</li><li>Your application requires high transactions</li><li>Data integrity is essential</li><li>You don’t anticipate a lot of changes in the schema</li></ul><h3>Reasons to use a NoSQL database</h3><ul><li>You store large amounts of data with no structure</li><li>You keep getting Unrelated, indeterminate, or evolving data requirements</li><li>Speed and scalability are critical.</li><li>When data integrity is not your top goal and you are concerned about the availability (&amp; eventual consistency will be good enough for your use case)</li></ul><p>I hope this helps you understand what you need to think about when selecting your database. What additional questions do you think about while selecting a database? Let me know your thoughts in the comments.</p><p>Happy coding! 💻</p><p>(If you find any doubts, updates, or corrections to improve this article, Feel free to share them in the comments) 😊</p><h3>Starting out with Web Development?</h3><p>Check out <a href="https://gumroad.com/a/316675187"><strong>HTML To React: The Ultimate Guide</strong></a></p><p>This ebook is a comprehensive study guide that will teach you <strong>everything you need to know to be a confident web developer through a ton of easy-to-understand examples and proven roadmaps</strong></p><p>With this <a href="https://gumroad.com/a/316675187"><em>link</em></a>, you can get <strong>60% OFF.</strong></p><figure><a href="https://gumroad.com/a/316675187"><img alt="HTML TO REACT" src="https://cdn-images-1.medium.com/max/1005/1*ggbWpRH6k48HHshG0sli6A.png" /></a><figcaption>HTML TO REACT: THE COMPLETE WEB DEVELOPMENT E-BOOK</figcaption></figure><p><em>(Originally published at </em><a href="https://apoorvtyagi.tech/how-to-choose-the-right-database-for-your-application"><em>https://apoorvtyagi.tech</em></a><em>)</em></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Check out our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Community Discord</em></strong></a><em> and join our </em><a href="https://inplainenglish.pallet.com/talent/welcome"><strong><em>Talent Collective</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11475c9ff242" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-choose-the-right-database-for-your-application-11475c9ff242">How to Choose the Right Database for Your Application</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles in Java]]></title>
            <link>https://apoorvtyagi.medium.com/solid-principles-in-java-fe75382d8923?source=rss-f4730edde1e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe75382d8923</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Apoorv Tyagi]]></dc:creator>
            <pubDate>Sat, 29 Jan 2022 19:35:36 GMT</pubDate>
            <atom:updated>2022-01-30T05:10:04.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nsGbzPxQs4y3FJuU" /></figure><p>In software engineering, <strong>SOLID</strong> is an acronym for 5 <a href="https://principles.design/">design principles</a> intended to make software designs more understandable, flexible, robust, and maintainable. Adopting these practices can contribute to avoiding code smells too.</p><p>The 5 SOLID principles are:</p><ul><li><strong>S</strong> — The single-responsibility principle</li><li><strong>O</strong> — The open-closed principle</li><li><strong>L</strong> — The Liskov substitution principle</li><li><strong>I</strong> — The interface segregation principle</li><li><strong>D</strong> — The dependency inversion principle</li></ul><p>Although the SOLID principles apply to any programming language, in further section I will be explaining each of them with examples written specifically in JAVA.</p><h3>Single Responsibility Principle</h3><p>This principle states that “ <strong>a class should have only one reason to change</strong> “ which means every class should have a single responsibility.</p><pre>public class Vehicle {<br>    public void details() {}<br>    public double price() {}<br>    public void addNewVehicle() {}<br>}</pre><p>Here the class has multiple reasons to change because the Vehicle class has three separate responsibilities: printing details, printing price, and adding a new vehicle to Database.</p><p>To achieve the goal of the single responsibility principle, we should implement a separate class that performs a single functionality only.</p><pre>public class VehicleDetails {<br>    public void details() {}<br>}</pre><pre>public class CalculateVehiclePrice {<br>    public double price() {}<br>}</pre><pre>public class AddVehicle {<br>    public void addNewVehicle() {}<br>}</pre><h3>Open-Closed Principle</h3><p>This principle states that “ <strong>software entities (classes etc.) should be open for extension, but closed for modification</strong> “. This means without modifying anything in a class, it should be extendable.</p><p>Let’s understand this principle with an example of a notification service:</p><pre>public class NotificationService{<br>    public void sendNotification(String medium) {<br>         if (medium.equals(&quot;email&quot;)) {}<br>    }<br>}</pre><p>Here, if you want to introduce a new medium other than email, let’s say send a notification to a mobile number then you need to modify the source code in NotificationService class.</p><p>So to overcome this you need to design your code in such a way that everyone can reuse your feature by extending it and if they need any customization they can extend the class and add their feature on top of it.</p><p>You can create a new interface like:</p><pre>public interface NotificationService {<br>    public void sendNotification(String medium);<br>}</pre><p>Email Notification:</p><pre>public class EmailNotification implements NotificationService {<br>    public void sendNotification(String medium){<br>        // write Logic using for sending email<br>    }<br>}</pre><p>Mobile Notification:</p><pre>public class MobileNotification implements NotificationService {<br>    public void sendNotification(String medium){<br>        // write Logic using for sending notification via mobile<br>    }<br>}</pre><h3>Liskov Substitution Principle</h3><p>This principle states that “ <strong>derived classes must be able to substitute for their base classes</strong> “. In other words, if class A is a child of class B, then we should be able to replace B with A without interrupting the current behavior of the program.</p><p>Consider an example of a square class derived from the Rectangle base class:</p><pre>public class Rectangle {<br>    private double height;<br>    private double width;<br>    public void setHeight(double h) { height = h; }<br>    public void setWidht(double w) { width = w; }<br>}</pre><pre>public class Square extends Rectangle {<br>    public void setHeight(double h) {<br>        super.setHeight(h);<br>        super.setWidth(h);<br>    }<br>    public void setWidth(double w) {<br>        super.setHeight(w);<br>        super.setWidth(w);<br>    }<br>}</pre><p>In the Rectangle class, setting the width, and height seem perfectly logical. However, in the square class, the SetWidth() and SetHeight() don&#39;t make sense because setting one would change the other to match it.</p><p>In this case, Square fails the Liskov substitution test because you cannot replace the Rectangle base class with its derived class Square. The Square class has extra constraints, i.e., the height and width must be the same. Therefore, substituting Rectangle with Square class may result in unexpected behavior.</p><h3>Interface Segregation Principle</h3><p>This principle applies to Interfaces and it is similar to the single responsibility principle. It states that “<strong> a client should never be forced to implement an interface that it doesn’t use, or clients shouldn’t be forced to depend on methods they do not use.</strong> “.</p><p>Let’s understand this by the example of a vehicle interface:</p><pre>public interface Vehicle {<br>    public void drive();<br>    public void stop();<br>    public void refuel();<br>    public void openDoors();<br>}</pre><p>Let’s say we now create a Bike class using this Vehicle interface</p><pre>public class Bike implements Vehicle {<br>    public void drive() {}<br>    public void stop() {}<br>    public void refuel() {}</pre><pre>    // Can not be implemented<br>    public void openDoors() {}<br>}</pre><p>Since Bike doesn’t have doors we can’t implement the last function.</p><p>To fix this, it is recommended to break down the interfaces into small multiple, interfaces so that no class is forced to implement any interface or methods, that it does not need.</p><pre>public interface Vehicle {<br>    public void drive();<br>    public void stop();<br>    public void refuel();<br>}</pre><pre>public interface Doors{<br>    public void openDoors();<br>}</pre><p>Creating two classes — Car and Bike</p><pre>public class Bike implements Vehicle {<br>    public void drive() {}<br>    public void stop() {}<br>    public void refuel() {}<br>}</pre><pre>public class Car implements Vehicle, Door {<br>    public void drive() {}<br>    public void stop() {}<br>    public void refuel() {}<br>    public void openDoors() {}<br>}</pre><h3>Dependency Inversion Principle</h3><p>The Dependency Inversion Principle (DIP) states that “ <strong>entities must depend on abstractions (abstract classes and interfaces), and not on concrete implementations (classes). Also, the high-level module must not depend on the low-level module, but both should depend on abstractions</strong>”.</p><p>Suppose there is a book store that enables customers to put their favorite books on a particular shelf.</p><p>In order to implement this functionality, we create a Book class and a Shelf class. The Book class will allow users to see reviews of each book they store on the shelves. The Shelf class will let them add a book to their shelf. For example,</p><pre>public class Book {<br>    void seeReviews() {}<br>}</pre><pre>public class Shelf {<br>     Book book;<br>     void addBook(Book book) {}<br>}</pre><p>Everything looks fine, but as the high-level Shelf class depends on the low-level Book, the above code violates the Dependency Inversion Principle. This becomes clear when the store asks us to enable customers to add their own reviews to the shelves, too. In order to fulfill the demand, we create a new UserReview class:</p><pre>public class UserReview{<br>     void seeReviews() {}<br>}</pre><p>Now, we should modify the Shelf class so that it can accept User Reviews, too. However, this would clearly break the Open/Closed Principle too.</p><p>The solution is to create an abstraction layer for the lower-level classes (Book and UserReview). We’ll do so by introducing the Product interface, both classes will implement it. For example, the below code demonstrates the concept.</p><pre>public interface Product {<br>    void seeReviews();<br>}</pre><pre>public class Book implements Product {<br>    public void seeReviews() {}<br>}</pre><pre>public class UserReview implements Product {<br>    public void seeReviews() {}<br>}</pre><p>Now, the Shelf can reference the Product interface instead of its implementations (Book and UserReview). The refactored code also allows us to later introduce new product types (for instance, Magazine) that customers can put on their shelves, too.</p><pre>public class Shelf {<br>    Product product;<br>    void addProduct(Product product) {}<br>    void customizeShelf() {}<br>}</pre><h3>Conclusion</h3><p>In this article, you were presented with the five principles of the SOLID Code. Adhering to SOLID principles can make your project, extendable, easily modifiable, well tested, with fewer complications.</p><p><em>Originally published at </em><a href="https://apoorvtyagi.tech/solid-principles-in-java"><em>https://apoorvtyagi.tech</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe75382d8923" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Asynchronous Processing and Message Queues]]></title>
            <link>https://apoorvtyagi.medium.com/introduction-to-asynchronous-processing-and-message-queues-a6b83e3c39e1?source=rss-f4730edde1e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6b83e3c39e1</guid>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Apoorv Tyagi]]></dc:creator>
            <pubDate>Fri, 31 Dec 2021 06:39:46 GMT</pubDate>
            <atom:updated>2022-01-22T06:25:24.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZdViWSGDs3WIZe0-rs1zaA.jpeg" /></figure><h3>Introduction</h3><p>In a client-server architecture, the client can request a job to be done from the server by sending messages between each other.</p><p>Handling this communication can increase in complexity when you begin to manage the rate at which messages are sent, the number of requests a server can handle, or the response time which the client demands.</p><p>In this blog, we’ll see one way to handle this intricacy.</p><h3>What is Synchronous Processing?</h3><p>In synchronous processing, a client sends a request to the server and waits for the server to complete its job and send back the response before the client can resume doing any other work.</p><p>This process is often referred to as a <em>blocking</em> request as the client gets blocked from doing any other work until a response is received.</p><h3>What is Asynchronous Processing?</h3><p>Asynchronous processing is the exact opposite of synchronous processing. Here, the client doesn’t wait for a response after sending a request to the server and continues doing any other work.</p><p>This process is referred to as a <em>non-blocking</em> request as the execution thread of the client is not blocked. This allows systems to scale as more work can be done in a given amount of time.</p><h3>Synchronous vs Asynchronous Processing</h3><ul><li>Synchronous requests block the execution thread of the client, forcing them to wait for the response to come before they can perform another action. On the other hand, asynchronous requests do not block and allow for more work to be done in a given time.</li><li>Since we do not know much time the request will take, it is difficult to build responsive applications with synchronous processing. The more blocking operations, the slower system becomes. With asynchronous processing, response time is quick as the client does not have to wait on the request.</li><li>Fault tolerance of asynchronous processing is higher than that of synchronous processing, as it is easy to build a retry mechanism when a request fails.</li></ul><figure><img alt="Async v/s Sync" src="https://cdn-images-1.medium.com/max/450/0*Lj2wY7zHSwgtLU2Q" /></figure><h3>What are Message Queues?</h3><p>A message queue is a component that buffers requests from one service and broadcasts asynchronously to another service.</p><p>Here, clients are the message producers, who send request messages to the queue instead of any server. They get an acknowledgment when the message is added to the queue, which enables them to continue with their other jobs without having to wait for the server.</p><p>Servers are known as message consumers and are served these messages from the queue based on the number of requests they can serve at any given time. This continues until all the messages in the queue have been served.</p><p>The two most common messaging queues are — <a href="https://www.rabbitmq.com/">RabbitMQ</a> and <a href="https://kafka.apache.org/">Kafka</a>.</p><h3>Structure of Message Queues</h3><p>A message queue is primarily a broker of messages between message producers and message consumers.</p><p>Each distinct entity in the messaging queue setup (producers, consumers, and queue) has a responsibility and they’re decoupled from each other as much as possible.</p><p>The only contract between all entities is the messages for which the message queue facilitates the movement from producers to consumers.</p><p>In the following sections, we will discuss the responsibilities of each component and look at the various modes with which the message queue delivers a message to consumers.</p><h3>Message Producers</h3><p>Message producers initiate the asynchronous processing request. Producers have a responsibility to generate a valid message and publish it to the message queue. Messages submitted to the queue are then queued up and delivered to consumers to be processed asynchronously.</p><p>Producers communicate with message queues using the Advanced Message Queuing Protocol (AMQP).</p><h3>Message Brokers</h3><p>A message broker is simply just a queue. You can even implement a simple broker programmatically that buffers messages and sends them to consumers as and when needed.</p><p>Message brokers are the actual decoupling elements in the setup, sitting between and managing the process of communication between producers and consumers.</p><p>Because of their simplicity, brokers are optimized for high concurrency and throughput.</p><p>It is important to note that adding message brokers introduces an extra layer of complexity into your infrastructure and requires you to scale them as well. Brokers also have specific requirements and limitations when it comes to scalability.</p><h3>Message Consumers</h3><p>The main responsibility of consumers is to receive and process messages from the queue.</p><p>Most consumers are API services that perform that actual asynchronous processing.</p><p>Consumers can be implemented in different application languages or technologies and maintained independently from other components.</p><p>To achieve decoupling, consumers should know nothing about the producers. The only contract that should exist between the two is valid messages from the queue.</p><p>When properly decoupled, consumers can serve as independent service layers that can be used by both the message queue setup and other components in your infrastructure.</p><h3>Consumer Communication Strategies</h3><p>Message queues need to transmit messages down to consumers, depending on how application developers implement consumers, message queues have three distinct ways of delivering messages to the consumers:</p><ul><li><strong>Pull Model</strong></li></ul><p>In this model, the consumer periodically checks the status of the queue. This is done at a scheduled interval programmed on the side of the consumer.</p><p>If there are messages found in the queue, the consumer picks them up until there are no more messages left to process, or when the ’N’ number of messages has been consumed. This ’N’ can be configured on the message broker.</p><ul><li><strong>Push Model</strong></li></ul><p>Once a message is added, the consumer is notified and the message is then pushed down to it. Messages are pushed down to consumers at a rate at which the consumer can easily regulate.</p><ul><li><strong>Subscription Model</strong></li></ul><p>In this model, consumers can subscribe to a topic. This publisher publishes a message to a topic rather than a queue. Each consumer connected to the broker maintains its private queue to receive messages from topics.</p><p>After the consumers subscribe to the topics and when a message is published to that topic, the message is cloned for each subscriber and added to the consumer’s private queue.</p><h3>Comparing Different Message Brokers</h3><p>As we have seen above, for asynchronous communication we usually need a message broker.</p><p>Below are the few considerations you have to look at when choosing a broker for managing your asynchronous operations:</p><ul><li><strong>Scale</strong>: The number of messages sent per second in the system</li><li><strong>Data Persistency</strong>: The capability to recover messages</li><li><strong>Consumer Capability</strong>: The capability to manage one-to-one / one-to-many consumers</li></ul><h3>RabbitMQ</h3><ul><li>Scale: Based on configuration and resources.</li><li>Persistency: Both persistent and transient messages are supported.</li><li>One-to-one vs One-to-many consumers: Both.</li></ul><p>RabbitMQ supports all major languages, including Python, Java, .NET, PHP, Ruby, JavaScript, Go, Swift, and more.</p><h3>Kafka</h3><ul><li>Scale: Can send up to a million messages per second.</li><li>Persistency: Yes.</li><li>One-to-one vs One-to-many consumers: Only one-to-many</li></ul><p>Kafka has managed SaaS on both Azure and AWS. Kafka also supports all major languages, including Python, Java, C/C++, Clojure, .NET, PHP, Ruby, JavaScript, Go, Swift, and more.</p><h3>Redis</h3><ul><li>Scale: Can send up to a million messages per second.</li><li>Persistency: Not supported (it’s an in-memory database).</li><li>One-to-one vs One-to-many consumers: Both.</li></ul><p>Redis is a bit different from the other message brokers. Redis is an in-memory data store. Originally, Redis only supported one-to-one communication with consumers. However, since Redis 5.0 introduced the pub-sub, you can have one-to-many as another option.</p><h3>Conclusion</h3><p>In this blog, we covered how asynchronous processing is advantageous over its counterparts and how a message queue helps us achieve asynchronous processing along with keeping the different entities in its setup decoupled from each other.</p><p>We also covered some basic characteristics of the most commonly used message brokers: Redis, Kafka, and RabbitMQ.</p><p>Here’s a bit more instruction for selecting the right message broker to use according to different use cases:</p><p><strong>Short-lived Messages: Redis</strong></p><ul><li>Redis is good for short-lived messages where persistence isn’t required.</li></ul><p><strong>Large Amounts of Data: Kafka</strong></p><ul><li>Kafka is good for storing a large amount of data for long periods. Kafka is also ideal for one-to-many use cases where persistency is required.</li></ul><p><strong>Complex Routing: RabbitMQ</strong></p><ul><li>RabbitMQ is good for complex routing communication.</li></ul><p>Happy coding! 💻</p><p>(If you find any doubts, updates, or corrections to improve this article, Feel free to share them in the comments) 😊</p><h3>Starting out with Web Development?</h3><p>Check out <a href="https://gumroad.com/a/316675187"><strong>HTML To React: The Ultimate Guide</strong></a></p><p>This ebook is a comprehensive study guide that will teach you <strong>everything you need to know to be a confident web developer through a ton of easy-to-understand examples and proven roadmaps</strong></p><p>With this link, you can get <strong>60% OFF.</strong></p><figure><a href="https://gumroad.com/a/316675187"><img alt="HTML TO REACT" src="https://cdn-images-1.medium.com/max/1005/1*ggbWpRH6k48HHshG0sli6A.png" /></a><figcaption>HTML TO REACT: THE COMPLETE WEB DEVELOPMENT E-BOOK</figcaption></figure><p><em>(Originally published at </em><a href="https://dev.to/apoorvtyagi/introduction-to-asynchronous-processing-and-message-queues-27od"><em>https://dev.to/apoorvtyagi.</em></a><em>)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6b83e3c39e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5++ Cool Python Snippets]]></title>
            <link>https://python.plainenglish.io/five-cool-python-snippets-6710951dfc26?source=rss-f4730edde1e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6710951dfc26</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Apoorv Tyagi]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 04:27:41 GMT</pubDate>
            <atom:updated>2021-11-30T07:03:11.951Z</atom:updated>
            <content:encoded><![CDATA[<h4>A list of useful Python snippets.</h4><figure><img alt="5++ cool Python snippets | Apoorv Tyagi" src="https://cdn-images-1.medium.com/max/1024/0*Fi-C475qK3nQ5q95" /></figure><p>Python is one of the world’s most popular and in-demand programming languages. This is for many reasons:</p><ul><li>Easy to learn</li><li>Versatile</li><li>Huge range of modules and libraries</li></ul><p>I almost use Python daily. Along the way, I’ve picked up a few clever yet useful tricks and tips that will surely make you think hard.</p><p>Here, I’ve shared 5++ of them 😉</p><h3>1. Careful with chained operations</h3><pre>&gt;&gt;&gt; (False == False) in [False] # makes sense<br>False<br>&gt;&gt;&gt; False == (False in [False]) # makes sense<br>False<br>&gt;&gt;&gt; False == False in [False] # now what?</pre><p>The first two make sense but what do think the third one will print? Even if you give ‘==’ precedence over ‘in’ or do it otherwise in both cases you’ll get the answer as ‘False’ but it is wrong. Why?</p><p>This is because all comparison operations in Python have the same priority when they’re chained together (i.e when you don’t use brackets). What this means is :</p><blockquote><em>If a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then (a op1 b op2 c … y opN z) is equivalent to (a op1 b )and (b op2 c) and … (y opN z).</em></blockquote><p>So the third expression will evaluate as (False == False) and (False in [False]) Which comes out to be <strong>True</strong>.</p><p>To learn more about it, head over to this <a href="https://docs.python.org/3/reference/expressions.html#comparisons">LINK</a></p><h3>2. Leakage of Loop variables</h3><pre>for x in range(7):<br>    if x == 6:<br>        print(x)<br>print(x)</pre><p>The first print statement seems pretty easy, right? It will simply print 6 because of the if condition that we have put. But what about the second print statement?</p><p>Should it not throw an error as variable ‘x’ is now out of scope &amp; x was never defined outside the scope of for loop.</p><p>But actually, it will print ‘6’ again. This is because, in Python, for-loops use the scope they exist in and leave their defined loop-variable behind.</p><p>This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.</p><p>In simple words, python does not have blocks, unlike C/C++ or Java. The only scoping unit in Python is a function. If you declare a variable in a function, you can use it anywhere inside it without having any problem.</p><p><em>If you are a </em><strong><em>Javascript </em></strong><em>enthusiast then there is something more for you</em>😉</p><p>If you translate that code to javascript, it would first print ‘6’ and then ‘7’. The reason for this is the way we iterate in python. The set of values that variable ‘x’ will take is explicitly determined before starting the ‘for loop’. This is not the case with javascript.</p><h3>3. Default mutable arguments</h3><pre>def func(default_arg=[]):<br>    default_arg.append(&quot;python&quot;)<br>    return default_arg</pre><pre>print(func())<br>print(func())<br>print(func())</pre><p>What do you think will be the output of the above code? It’s very intuitive to think that we will get :</p><pre>[&#39;python&#39;]<br>[&#39;python&#39;]<br>[&#39;python&#39;]</pre><p>But again this is not the case. A default argument is a mutable object like ‘list’ in our case, Python creates it when you define the function, and not every time you invoke it.</p><p>Instead, the recently assigned value to them is used as the default value every time they’re invoked.</p><p>So the correct output will be :</p><pre>[&#39;Python&#39;] <br>[&#39;python&#39;, &#39;python&#39;] <br>[&#39;python&#39;, &#39;python&#39;, &#39;python&#39;]</pre><blockquote><em>NOTE: When we explicitly pass [] to “func” as the argument, the default value of the default_arg variable will not be used, so the function will returned as expected i.e [‘python’] [‘python’] [‘python’].</em></blockquote><p>To learn more about mutable/immutable objects in python, check out this <a href="https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/">LINK</a></p><h3>4. Keep trying</h3><pre>def func():<br>    try:<br>        return &#39;from_try&#39;<br>    finally:<br>        return &#39;from_finally&#39;</pre><pre>print(func()) #What will get printed?</pre><p>If you look at the above code carefully, you’ll see a return statement inside the ‘try’ block. According to that, it should print “from_try” as the output.</p><p>But <a href="http://docs.python.org/reference/compound_stmts.html#the-try-statement">Python docs</a> state:</p><blockquote><em>When a </em><strong><em>return</em></strong><em>, </em><strong><em>break </em></strong><em>or </em><strong><em>continue </em></strong><em>statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’</em></blockquote><p>The return value of a function is determined by the last return statement executed. Since the <strong>finally</strong> clause always executes, a return statement executed in the <strong>finally </strong>clause will always be the last one executed. Hence the correct output will be from_finally.</p><h3>5. What is wrong with “is”</h3><pre>&gt;&gt;&gt; a = 256<br>&gt;&gt;&gt; b = 256<br>&gt;&gt;&gt; a is b<br>True</pre><pre>&gt;&gt;&gt; a = 257<br>&gt;&gt;&gt; b = 257<br>&gt;&gt;&gt; a is b<br>&gt;&gt;&gt; ?</pre><p>Since the first one is True, the second one should also be True. isn’t it?</p><p>Well no. The correct answer is <strong>False</strong>. The reason being 256 is an existing object but 257 isn’t.</p><p>What I mean by this statement is When you start up python the numbers from -5 to 256 will be allocated. These numbers are used a lot, so it makes sense just to have them ready.</p><p>According to the python docs:</p><blockquote><em>The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you just get back a reference to the existing object.</em></blockquote><p>This is why when you assigned a &amp; b to 257, two different references are generated &amp; the “is” operator checks if both the operands refer to the same object which is not true in this case.</p><p>So those were the 5 cool quirks of python. I hope you liked them &amp; hopefully learned something new. But since the title contains “ Five<strong>++</strong> python snippets”, I have one extra piece for you all which I am sure you will like 👇</p><h3>5++. Emojis in Python 🐍</h3><p>Do you know you can use Emojis in your Python code?</p><p>Yes, <a href="https://pypi.org/project/emoji/">It’s true</a></p><pre>&gt;&gt;import emoji<br>&gt;&gt;print(emoji.emojize(&#39;Python is amazing:thumbs_up:&#39;))<br>Python is amazing👍</pre><p>Here’s your whole <a href="https://www.webfx.com/tools/emoji-cheat-sheet/">emoji cheat sheet</a>. Go on &amp; try it out…</p><p><em>Originally published at </em><a href="https://apoorvtyagi.tech/cool-python-snippets-that-will-blow-your-mind"><em>https://apoorvtyagi.tech</em></a><em>.</em></p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6710951dfc26" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/five-cool-python-snippets-6710951dfc26">5++ Cool Python Snippets</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing a URL-Friendly Unique Identifier — NanoID]]></title>
            <link>https://javascript.plainenglish.io/introducing-a-url-friendly-unique-identifier-nanoid-fbf4d2162322?source=rss-f4730edde1e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbf4d2162322</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Apoorv Tyagi]]></dc:creator>
            <pubDate>Tue, 12 Oct 2021 04:21:19 GMT</pubDate>
            <atom:updated>2021-10-12T05:19:44.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducing a URL-Friendly Unique Identifier — NanoID</h3><figure><img alt="Nano Id — By Apoorv Tyagi" src="https://cdn-images-1.medium.com/max/1024/1*Lfvd2z5QkGQSM5eq2gSd-A.png" /></figure><h3>Introduction</h3><p>In every software system, we need unique Ids to distinguish between several objects from one another.</p><p>Recently, I wrote about the <a href="https://medium.com/nerd-for-tech/unique-id-generation-in-distributed-systems-6f7aaa39c9af">unique Id generation for a large-scale distributed environment</a>. In that article, we touched a little on UUIDs.</p><p>In this blog post, I will share an alternative to UUIDs that can help you fit the requirements that UUIDs fulfills and overcomes some of their shortcomings as well.</p><h3>Introducing Nano ID</h3><p>It is a tiny, secure, URL-friendly, unique string ID generator.</p><ul><li><strong>Nano ID has a smaller size as compared to UUID</strong>. This size reduction impacts a lot. Making use of NanoID is easier for transferring information and storage space. In a large-scale system, these numbers can make a lot of difference.</li><li><strong>NanoID uses a cryptographically strong API which is a lot safer</strong> compared to Math.Random() which are <a href="https://franklinta.com/2014/08/31/predicting-the-next-math-random-in-java/">insecure</a>. These API modules use unpredictable hardware-generated random identifiers.</li><li><strong>NanoID utilizes its very own “uniform formula” throughout the application</strong> of the ID generator instead of making use of an arbitrary % alphabet which is a popular mistake to make when coding an ID generator (The spread will not be even in some cases).</li><li><strong>NanoID uses a larger alphabet</strong> resulting in short but unique identifiers.</li><li><strong>NanoID permits designers to utilize personalized alphabets</strong>. This is another additional function of Nano ID. You can alter the literals or the dimension of the id as shown below (Specifying personalized letter as ‘1234567890ABCDEF’ &amp; dimension of the Id as 10):</li></ul><pre>import { alphabet } from &#39;nanoid&#39;; <br>const nanoid = alphabet (&#39;1234567890ABCDEF&#39;, 10); <br>model.id = nanoid();</pre><ul><li><strong>NanoID doesn’t much rely on any kind of third-party dependencies</strong>, which means, it ends up being a lot more steady which is helpful to maximize the package scope over time as well as make it much less vulnerable to the issues that come along with dependencies.</li><li><strong>NanoID is available in various programs languages</strong>, which include — C#, C++, Dart &amp; Flutter, Go, Java, PHP, Python, Ruby, Rust, Swift, etc.</li></ul><h3><a href="https://github.com/ai/nanoid#benchmark">Benchmark</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*TQF-XxYrA6TLJgtu" /></figure><h3>Example usages</h3><p>Generating both NanoID or UUID is pretty straightforward. In JavaScript, you have NPM packages that will help you to generate them. You can get NanoId from here =&gt; <a href="https://github.com/ai/nanoid">github.com/ai/nanoid</a></p><ul><li>The main module uses URL-friendly symbols (A-Za-z0–9_-) and returns an ID with 21 characters:</li></ul><pre>import { nanoid } from &quot;nanoid&quot;;<br>model.id = nanoid() // X2JaSYP7_Q2leGI9b-MyA</pre><ul><li>You can also specify the number of characters you want:</li></ul><pre>nanoid(9); // &quot;wMeKBp6th&quot;</pre><ul><li>You can also change the used alphabet for generating hashes to your own if you have specific requirements as seen above:</li></ul><pre>const alphabet = &#39;0123456789ABCDEF&#39;;<br>generate(alphabet, 9); // F65BF3050</pre><h3>Risk of collision</h3><p>Even though it can generate over 2.2 million unique IDs per second with its default alphabet, there is still a chance of generating the same multiple Ids.</p><p>But what are the odds of that happening?</p><p>You can calculate that based on the given parameters easily <a href="https://zelark.github.io/nano-id-cc/">here</a> and <a href="https://alex7kom.github.io/nano-nanoid-cc/">here</a>.</p><p>You’ll notice that this <strong>probability comes out to be extremely small.</strong></p><h3>Some disadvantages</h3><ul><li><strong>Being non-human readable can be one of the disadvantages in some cases</strong></li></ul><p>Imagine that a customer calls and is asked to provide the identifier, having to spell a complete NanoID is not a pleasant experience. When compared to UUID, NanoID is way shorter and readable but still cannot be used in such cases where the end customer needs to use it.</p><ul><li><strong>It can’t be used as a primary key in any SQL Database tables</strong></li></ul><p>If you use NanoID as a table’s primary key, there will be problems if you use the same column as a clustered index. This is because <strong>NanoIDs are not sequential.</strong></p><p>This is because the nature of NanoID(or even UUID) is that it’s random and a clustered index physically orders the records by the key, so for every insert if there are indexes on the table, the database must make sure the new entry is also found via these indexes and to keep the index order and tree balance.</p><p>For this SQL has to reorder the records on disk and therefore remove clustering from this index. But when you have something sequential like time — clustering is almost free and easy to do after inserting a new record.</p><h3>A few words of wisdom</h3><p>Any approach in a Software World is always going to be subjective. It’s up to your requirements to weigh in the tradeoffs and choose the approach that works for you. No design is concrete enough to continue forever, so given the constraints, we have chosen a certain design, and depending on how it works for us we might evolve it further as well.</p><p>👋 Thanks for reading and happy learning!</p><p><em>Originally published at </em><a href="https://apoorvtyagi.tech/nanoid-url-friendly-unique-id"><em>https://apoorvtyagi.tech</em></a><em>.</em></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbf4d2162322" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/introducing-a-url-friendly-unique-identifier-nanoid-fbf4d2162322">Introducing a URL-Friendly Unique Identifier — NanoID</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>