<?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 Jorge Felipe Quintero on Medium]]></title>
        <description><![CDATA[Stories by Jorge Felipe Quintero on Medium]]></description>
        <link>https://medium.com/@jorgefelipeqs?source=rss-ba71abadcbe7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*g9a6KdJ1mJzDXVc8</url>
            <title>Stories by Jorge Felipe Quintero on Medium</title>
            <link>https://medium.com/@jorgefelipeqs?source=rss-ba71abadcbe7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:43:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jorgefelipeqs/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[Why developer interviews now hinge on the second question]]></title>
            <link>https://medium.com/@jorgefelipeqs/why-developer-interviews-now-hinge-on-the-second-question-53d6f2974979?source=rss-ba71abadcbe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/53d6f2974979</guid>
            <dc:creator><![CDATA[Jorge Felipe Quintero]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 10:46:49 GMT</pubDate>
            <atom:updated>2026-09-30T10:46:49.754Z</atom:updated>
            <content:encoded><![CDATA[<p>When I interview a junior developer, I usually ask about the SOLID principles. Most candidates can list all five, often in one breath, like something memorized the night before. Then I ask which of the five has to do with inheritance, and a surprising number of them go blank. That gap, between reciting a definition and being able to do something with it, is what I think the development market is filtering for right now.</p><p>You have probably met people who do specific things reasonably well, who can repeat an action until they get it right, who have their unfair advantages like everyone else, and who might strike you as intelligent after an afternoon of conversation. Then you watch one of them pick up a can with a pull tab and go looking for a knife.</p><p>The scene sounds like a joke, but it describes a real split. There is intelligence as an adjective, the label you hang on someone because they speak well, know about a lot of topics, and left a good impression. And there is measurable ability, the thing that shows up when that same person faces something they have never seen and has to make it work. The first is visible in conversation. The second only becomes visible when there is a problem on the table.</p><p>The British philosopher Gilbert Ryle named this distinction in 1949, in The Concept of Mind. He separated knowing that, knowing that something is true, from knowing how, being able to do it. And he argued that knowing how doesn’t come from piling facts into your head. You can know perfectly well that the can has a pull tab and still not know how to use it.</p><p>Since I finished school, I have rarely been the most intelligent person at the table. I never developed mastery of anything ultra-complex. What I am is someone who gets things resolved, and that is what took me into software development with no formal studies, from a job as a security guard. The obvious question is what I did differently, and I think the answer fits inside that interview question.</p><p>First, though, the route almost everyone takes when the market gets tough, which is to accumulate. Another course, another certification, another list of design patterns, a hundred interview questions memorized in a document. It makes sense, because it is what can be measured from the outside and it helps you sleep at night. But that route has a hard ceiling. It prepares you for questions that already exist, and a developer’s job consists precisely of the ones that don’t exist yet. A production bug at eleven at night doesn’t come with a study guide.</p><p>At some point you do have to internalize the patterns that already solve known problems. Nobody will pay you to reinvent transaction handling. But the pattern is a tool, and what the market pays for is knowing when to reach for it.</p><p>So when I interview a junior, I don’t need them to know every pattern. I want to see them thinking, even if what they’re doing is trying to remember the prep guide they put together with ChatGPT. That is a capable person. Someone who recites SOLID like a prayer and then freezes when I ask which principle concerns inheritance gives me very little.</p><p>The textbook answer is the L, the Liskov substitution principle. Barbara Liskov stated it in the late eighties, and in plain terms it says that if a class inherits from another, you must be able to use the child anywhere you used the parent without breaking the program. The classic example is a Square that inherits from Rectangle. It looks fine until some code sets the width and the height independently, as it is entitled to do with any rectangle, and the square can no longer honor both. But here is what I actually care about. If a candidate tells me they think it’s the O, because “open for extension” sounds like inheritance to them, and explains why, they’ve given me more than the one who rattled off all five letters. They’re half wrong and fully thinking.</p><p>That is the test I apply to everything else, and it comes down to asking a second question. Anyone knows the definition. What separates the two people in front of the can is what happens when you ask something the definition doesn’t answer directly, such as what the thing is for, when it breaks, or how it relates to something else.</p><p>This has a cost, and it should be stated plainly. At first, the person who solves looks worse. They’re slower, they ask more questions, they hesitate out loud, and in a quiz-style interview they lose to the one who memorized the answers. There are also HR filters that only scan your CV for keywords, and you don’t get past those by thinking well. If you decide to train the ability instead of the adjective, you will lose some hiring processes to someone better prepared for the exam. Pues ni modo, as we say in Spanish. That’s the price.</p><p>I do think the market is harder than it was five years ago. I don’t think it’s saturated. Companies used to be able to afford hiring developers who only recite, and now they understand they should hire only the ones who solve.</p><p>That luxury had a concrete economic explanation. In 2021 money was cheap. Interest rates in the United States were practically at zero, and hiring was close to a bet: bring people in, grow the team, and they would learn along the way. When the Federal Reserve started raising rates in 2022, every hire had to be justified. Someone who only recites costs the same salary as someone who solves, and on top of that costs hours of a senior’s time, because the senior ends up solving everything for them. In a company that no longer has free money, that math doesn’t work.</p><p>Then AI priced the memorized part at zero. If ChatGPT will recite SOLID for free in two seconds, nobody is going to pay you a salary to recite it. What keeps its value is exactly what the tool doesn’t do for you, which is noticing that the answer doesn’t fit your problem.</p><p>I can’t give you a figure for how many of the people hired in that period were the reciting kind. Nobody knows that with any certainty. What I do see is that interviews have changed, and almost all of them ask the second question now. The claim can also be checked. If over the next few years companies go back to hiring in volume people who answer with definitions and go blank on the follow-up, and it works out for them, I was wrong. I don’t see that today.</p><p>The market ran out of money to pay people who only recite. So the next time you study something, don’t stop at the definition. Ask yourself the second question. And if the third one leaves you blank, good, because that’s where the work starts.</p><p>A Spanish video version of this piece is available on my YouTube channel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53d6f2974979" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LONGEST SUBSTRING WITHOUT REPEATING CHARACTERS]]></title>
            <link>https://medium.com/@jorgefelipeqs/longest-substring-without-repeating-characters-b99d6567e507?source=rss-ba71abadcbe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b99d6567e507</guid>
            <category><![CDATA[java-dsa]]></category>
            <category><![CDATA[dsa-problem]]></category>
            <category><![CDATA[dsa-training]]></category>
            <dc:creator><![CDATA[Jorge Felipe Quintero]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 00:27:34 GMT</pubDate>
            <atom:updated>2026-09-20T00:27:34.802Z</atom:updated>
            <content:encoded><![CDATA[<h4>AND THE JUMP THAT MAKES IT LINEAR</h4><h4>THE PROBLEM</h4><p>Given a string, return the length of the longest run of consecutive characters that contains no repeats. “abcabcbb” gives you 3, for “abc”. “bbbbb” gives you 1. “pwwkew” gives you 3, for “wke”.</p><p>Read that third example again before you write anything. “pwke” is longer and has no repeats, but it isn’t an answer, because it isn’t a substring. A substring is contiguous. Drop a character out of the middle and what you have is a subsequence, which is a different problem with a different solution. This is the first place people lose the problem, and they lose it in the reading, not in the coding.</p><p>The constraints matter too. The string can be up to 10⁵ characters, and it can contain letters, digits, symbols and spaces. Both of those facts are load-bearing, and I’ll come back to each.</p><p>THE OBVIOUS FIRST ATTEMPT</p><p>Every substring, checked. Two nested loops to pick a start and an end, and some way to decide whether the piece between them has a duplicate.</p><pre>    for (int start = 0; start &lt; n; start++) {<br>        for (int end = start; end &lt; n; end++) {<br>            if (hasNoDuplicates(s, start, end)) {<br>                longest = Math.max(longest, end - start + 1);<br>            }<br>        }<br>    }</pre><p>There are about n² / 2 substrings, and scanning each one for duplicates costs up to n more, so this is O(n³) in the worst case. You can cut that by building a set as you extend the end pointer instead of re-scanning from scratch, which drops it to O(n²). Either way, at n = 10⁵ you’re looking at something on the order of 10¹⁰ operations. Dead on arrival.</p><p>That “10⁵” in the constraints is a signal, by the way, and it’s worth training yourself to read it. A bound of a few thousand tolerates a quadratic solution. A bound of 10⁵ or more is the problem setter telling you they want O(n) or O(n log n). You can often eliminate an entire class of approaches before writing a line, just from the size of the input.</p><h4><strong>THE OBSERVATION THAT KILLS THE NESTED LOOP</strong></h4><p>Here’s the thing the brute force is wasting. Suppose you’re sitting on a window from index i to index j with no duplicates, and you extend to j+1 and hit a repeat. You now know something strong: no window starting at i and ending at j+1 or later will ever work. That duplicate isn’t going anywhere as long as i stays put. There’s no reason to keep testing longer windows from i, and no reason to ever restart the outer loop from i+1 and re-walk ground you’ve already covered.</p><p>So instead of two independent loops, you keep one window and move its edges. The right edge marches forward one character at a time. The left edge moves forward only when it has to, which is exactly when the new character collides with something already inside the window.</p><p>The straightforward way to write that uses a set:</p><pre>    Set&lt;Character&gt; window = new HashSet&lt;&gt;();<br>    int start = 0, longest = 0;<br>    for (int end = 0; end &lt; s.length(); end++) {<br>        while (!window.add(s.charAt(end))) {<br>            window.remove(s.charAt(start++));<br>        }<br>        longest = Math.max(longest, end - start + 1);<br>    }</pre><p>HashSet.add returns false when the element is already there, so the inner while loop keeps evicting characters from the left until the collision is gone.</p><p>Now, be honest about what this bought you. This is already O(n). Every character enters the set once and leaves at most once, so the inner loop can’t run more than n times in total across the whole execution, no matter how it looks nested on the page. That reasoning is called amortized analysis: you don’t bound the inner loop per iteration, you bound its total work across the run.</p><p>So the version I’m about to describe is not an asymptotic improvement. What it improves is the constant factor, and it does that in two ways: it replaces up to n one-step crawls and hash operations with a single assignment, and it swaps the hash set for a flat array. On a problem where the input is 10⁵ characters, that’s the difference between comfortable and borderline, not between passing and failing. I’d rather tell you that than sell you a fake speedup.</p><h4>THE KEY INSIGHT</h4><p>The left edge of the window never moves backward.</p><p>That’s it. That single property is what makes this problem linear, and it’s what lets you stop crawling and start jumping. If you know the position of the previous occurrence of the character you just consumed, you don’t need to walk the left edge over to it one step at a time. You can drop it directly to one past that occurrence, because every position in between was already ruled out.</p><p>But “never moves backward” is a property you have to actively enforce, not one you get for free. The stored position of a previous occurrence might be stale, referring to a character that fell out of the window a long time ago. If you jump unconditionally, you’ll drag the left edge backward and start reporting windows that contain duplicates. So the jump is guarded: take the stored position only if it’s actually ahead of where the left edge currently sits.</p><p>How would you have spotted this on your own? Ask one question whenever you’re scanning a sequence looking for the best range ending at each position: as the right edge moves forward by one, can the smallest valid left edge ever get smaller? Here it can’t, because adding a character to a window can only introduce a duplicate, never remove one. The constraint is monotone, so the window is one-directional, so you get a sliding window.</p><p>And the same question tells you when the pattern does not apply. Take “longest subarray with sum at most k” over an array that may contain negative numbers. Extending the right edge can now decrease the sum, which can make a previously invalid left edge valid again. The left boundary can move backward, the sliding window collapses, and you need prefix sums with a hash map instead. Same diagnostic question, opposite answer. That’s the part worth carrying to the next problem.</p><h4>THE PITFALLS</h4><p>The unguarded jump. This is the bug, and it’s easy to write:</p><pre>windowStart = positionAfterLastSeen[current]; // no guard</pre><p>Run “abba” through it. At index 2 you hit the second ‘b’, jump the left edge to 2, and the window is just “b”. At index 3 you hit ‘a’, whose last-seen position points back to the very start of the string, and the left edge slides backward to 1. Your window is now “bba”, you report a length of 3, and the correct answer is 2. It passes every example in the problem statement and fails on a four-character string.</p><p>Measuring before shrinking. Update your best length before moving the left edge and you’ll happily count a window that still contains the duplicate you just found. On “abba”, that reports 3 as well. Shrink first, measure second.</p><p>The sentinel collision. If your table stores raw indices and you initialize it to zero to mean “never seen”, then a character sitting at index 0 is indistinguishable from a character you’ve never encountered. Storing index + 1 instead, so that zero can only mean “unseen”, removes the ambiguity. Initializing the table to -1 works too. Picking neither is a silent wrong answer on strings whose first character reappears.</p><p>Sizing the table to the wrong alphabet. It’s tempting to write new int[26] because the problem says “letters”. Read the constraint again: digits, symbols and spaces. The first space in the input walks straight off the end of a 26-slot array.</p><h4>THE CODE</h4><pre>    class Solution {<br>        private static final int ASCII_ALPHABET_SIZE = 128;<br><br>        public int lengthOfLongestSubstring(String s) {<br>            int[] positionAfterLastSeen = new int[ASCII_ALPHABET_SIZE];<br>            int windowStart = 0;<br>            int longest = 0;<br><br>            for (int end = 0; end &lt; s.length(); end++) {<br>                char current = s.charAt(end);<br>                if (positionAfterLastSeen[current] &gt; windowStart) {<br>                    windowStart = positionAfterLastSeen[current];<br>                }<br>                longest = Math.max(longest, end - windowStart + 1);<br>                positionAfterLastSeen[current] = end + 1;<br>            }<br><br>            return longest;<br>        }<br>    }</pre><p>The whole solution is three lines of logic in a loop, and the `&gt;` on line four is doing more work than it looks like it is. It’s the enforcement of the monotonicity property, and it’s the difference between this code and the “abba” bug above.</p><h4>COMPLEXITY, AND ONE ASSUMPTION</h4><p>Time is O(n). The right edge visits each index exactly once. The left edge only ever increases and is bounded by n, so its total movement across the entire run is at most n. Every operation inside the loop is an array read, an array write and a comparison, all constant time.</p><p>Space is O(1). The table is 128 integers regardless of whether the input is 5 characters or 100,000.</p><p>That O(1) rests on an assumption worth stating out loud: that the input is ASCII. The array indexes directly by the char value, and a Java char runs to 65535. Feed this a non-ASCII character and you don’t get a wrong answer, you get an ArrayIndexOutOfBoundsException. For this problem’s test data that’s fine, and taking the fixed array is the right trade. Outside it, swap in a HashMap&lt;Character, Integer&gt; for the same asymptotics at a higher constant factor, and iterate by code point if you need to handle characters outside the basic multilingual plane. Knowing which assumption you took, and what breaks when it stops holding, is worth more than the assumption itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b99d6567e507" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[parallelStream in Java: Why "Parallel" Doesn't Always Mean "Faster"]]></title>
            <link>https://medium.com/@jorgefelipeqs/parallelstream-in-java-why-parallel-doesnt-always-mean-faster-d2733e3af606?source=rss-ba71abadcbe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2733e3af606</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Jorge Felipe Quintero]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 19:36:36 GMT</pubDate>
            <atom:updated>2026-04-13T19:36:36.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ExK0joJMXi1L8ard.png" /></figure><p>There’s a recurring temptation among Java developers: swapping .stream() for .parallelStream() expecting the code to automatically become faster. The reasoning seems harmless — if I have multiple cores available, why not use them? What few anticipate is that this decision, made without a real analysis of context, can not only be useless but actively detrimental to application performance.</p><p>This article takes a deep dive into the internal mechanics of parallelStream, the real conditions under which it delivers value, and the scenarios where it introduces more problems than it solves. The point isn&#39;t to avoid parallelism — it&#39;s to understand when the right tool is a different one.</p><h3>The Mirage of Free Parallelism</h3><p>Java 8 introduced the Streams API with an elegant promise: transform collections declaratively, and if the developer wants parallelism, just call .parallelStream() instead of .stream(). Internally, the framework handles splitting the work, distributing it across threads, and combining the results.</p><p>That simplicity at the interface level hides complex machinery underneath. And like every abstraction, it works well within its design assumptions — but collapses silently when those assumptions aren’t met.</p><p>The most frequent pattern of misuse looks like this:</p><pre>List&lt;String&gt; filtered = items.parallelStream()<br>    .filter(item -&gt; allowedCodes.parallelStream()<br>        .anyMatch(code -&gt; code.equals(item.getCode())))<br>    .collect(Collectors.toList());</pre><p>Someone wrote this thinking “parallel + parallel = twice as fast.” In reality, when items has 8 elements and allowedCodes has 3, what happens is that an entire inter-thread coordination machinery is activated to perform 24 string comparisons that a single core could complete in nanoseconds. The parallelization overhead exceeds the useful work by orders of magnitude.</p><p>To understand why, we need to open the black box.</p><h3>How parallelStream Works Internally</h3><h3>Spliterator: The Partitioning Strategy</h3><p>When parallelStream() is invoked on a collection, the first internal step is obtaining a Spliterator — an interface that defines how the data source can be divided into chunks processable in parallel.</p><p>For an ArrayList, the Spliterator implements a binary index-based split strategy: it divides the list in half, and each half can be recursively subdivided. This is efficient in terms of partitioning mechanics — O(1) per split — but it doesn&#39;t evaluate whether the work contained in each chunk justifies the division.</p><p>The Spliterator reports characteristics such as SIZED (knows the total size) and ORDERED (preserves encounter order). These characteristics influence the framework&#39;s decisions: for example, an ORDERED Spliterator forces the merge of results to respect the original sequence, which adds synchronization cost.</p><h3>From Spliterator to ForkJoinTask</h3><p>The stream pipeline is internally translated into a tree of ForkJoinTasks (specifically subclasses of CountedCompleter). The root task is recursively subdivided — each call to trySplit() generates a child subtask — until reaching an internal threshold defined by AbstractTask.LEAF_TARGET, which is typically four times the number of available processors.</p><p>Each leaf task executes the pipeline operation (filtering, mapping, reduction) over its segment of the Spliterator. When it finishes, it notifies its parent. When all children of a node complete, the parent executes the combine phase.</p><h3>The Combine Phase</h3><p>For a terminal operation like collect(Collectors.toList()), each subtask produces a partial list. In the combine phase, these lists are merged via addAll(). For operations like anyMatch, the framework implements short-circuiting: the first subtask that finds a match signals the others to cancel. But that cancellation is cooperative — tasks already running finish their current chunk before observing the signal.</p><h3>The Hidden Costs</h3><p>Every invocation of parallelStream pays a fixed price before a single line of the lambda executes.</p><p>Creating child Spliterator objects and ForkJoinTasks generates pressure on the garbage collector. Each task must be enqueued in the ForkJoinPool&#39;s work queue, which involves atomic operations (CAS) on concurrent structures. Inter-thread signaling involves kernel context switches. And the combine phase requires merging partial results, which for lists means copying internal arrays.</p><p>In a sequential pipeline, none of this happens. The Spliterator simply iterates element by element, on a single thread, with no coordination, no copying, no signaling.</p><p>For small collections with cheap per-element operations, these fixed costs completely dominate the useful work. The net result is that parallelStream is <strong>measurably slower</strong> than stream().</p><h3>ForkJoinPool: The Engine Behind the Curtain</h3><h3>The commonPool and Its Global Nature</h3><p>Every parallelStream in Java executes on ForkJoinPool.commonPool(), a JVM-wide singleton. Its default parallelism level is Runtime.getRuntime().availableProcessors() - 1. On a server with 8 cores, that means 7 worker threads shared across the entire application.</p><p>The key word is “shared.” The commonPool isn’t exclusive to the stream that invoked it. Every parallelStream, every CompletableFuture.supplyAsync() without an explicit executor, and potentially internal application frameworks all compete for those same 7 workers.</p><h3>Work-Stealing: Elegant but Conditional</h3><p>The ForkJoinPool implements a work-stealing model. Each worker has a deque (double-ended queue) of tasks. When a worker finishes its work, it steals tasks from the opposite end of another worker&#39;s deque. This enables dynamic load balancing without centralized coordination.</p><p>The model works extraordinarily well for a specific workload profile: <strong>CPU-bound</strong> tasks, of <strong>short duration</strong>, that recursively subdivide into similar subtasks. Parallel merge sort is the canonical example. Each subtask performs real computational work, returns the thread quickly, and work-stealing redistributes the load if one branch of the tree turned out heavier than another.</p><p>But this model has a fundamental assumption: <strong>workers must be doing work, not waiting</strong>. When a worker becomes blocked — waiting for an HTTP response, a database query, a disk read — it doesn’t return the thread to the pool. It sits there, occupying a pool slot, doing nothing, and unable to steal work from others.</p><h3>Anatomy of a Misuse: The Cargo Port Example</h3><p>To illustrate these concepts concretely, let’s imagine a management system for a maritime cargo port. The port operates with <strong>loading bays</strong> (typically between 5 and 15 active simultaneously), and each bay processes <strong>containers</strong> (potentially thousands per ship).</p><h3>Scenario 1: Filtering Bays by Status</h3><p>A developer needs to filter active bays by certain criteria — for example, which ones are assigned to a specific cargo type:</p><pre>// Approach with parallelStream (incorrect)<br>List&lt;LoadingBay&gt; filteredBays = activeBays.parallelStream()<br>    .filter(bay -&gt; allowedCargoTypes.parallelStream()<br>        .anyMatch(type -&gt; type.equals(bay.getCargoType())))<br>    .collect(Collectors.toList());</pre><p>Here activeBays has 12 elements and allowedCargoTypes has 4. The outer parallelStream activates fork/join for 12 bays. Inside each lambda, the inner parallelStream activates <em>another</em> level of fork/join for 4 cargo types. This generates fork/join tasks nested within fork/join tasks, all competing for the same commonPool workers.</p><p>The actual work is 48 string comparisons. The overhead is: creation of multiple Spliterators, dozens of ForkJoinTasks, enqueue into work queues with CAS operations, inter-thread signaling, and merging of partial results. The overhead-to-useful-work ratio is absurd.</p><p>The fix is straightforward:</p><pre>// Correct approach<br>Set&lt;String&gt; allowedTypes = new HashSet&lt;&gt;(allowedCargoTypes);<br>List&lt;LoadingBay&gt; filteredBays = activeBays.stream()<br>    .filter(bay -&gt; allowedTypes.contains(bay.getCargoType()))<br>    .collect(Collectors.toList());</pre><p>This code is faster (we eliminate the parallelization overhead <strong>and</strong> replace the linear search of anyMatch with an O(1) lookup in a HashSet), more readable, and correctly sequential for a collection that doesn&#39;t justify parallelism.</p><h3>Scenario 2: Processing Containers from a Full Ship</h3><p>Now imagine we need to classify 15,000 containers from a ship by their tariff category, an operation involving volumetric weight calculations, HS code validation, and business rule application — all purely computational:</p><pre>List&lt;ClassifiedContainer&gt; classified = shipContainers.parallelStream()<br>    .map(container -&gt; classifyByTariff(container))<br>    .collect(Collectors.toList());</pre><p>In this case, parallelStream <strong>does make sense</strong>. The collection is large (15,000 elements), the per-element work is significant and CPU-bound (microseconds of computation per container), there&#39;s no I/O, no shared state, and the ArrayList&#39;s Spliterator splits efficiently by index.</p><p>The difference between the two scenarios isn’t just quantitative — it’s qualitative. In the first, the per-element work is trivial (a string comparison); in the second, it’s substantial (a complex business calculation). Parallelism only amortizes its fixed cost when the per-element work is sufficiently expensive.</p><h3>The Special Problem of Nested Parallelism</h3><p>When a parallelStream is nested inside another, fork/join tasks execute within fork/join tasks, all on the same commonPool. This creates several problems.</p><p>First, there’s a contention issue: subtasks from the inner stream compete with those from the outer stream for the same workers, increasing signaling latency and reducing work-stealing efficiency. Second, the framework has no visibility that the parallelism is nested — it cannot reason about total load or adjust partitioning. Each nesting level multiplies the number of created tasks, amplifying overhead without proportional benefit.</p><p>The result is that nested parallelism almost never improves performance and frequently degrades it. If the outer stream operates on few elements (as is often the case when nesting), the benefit of outer parallelism is nil. If the inner stream operates on few elements, the benefit of inner parallelism is nil. If both operate on few elements, you pay the coordination overhead twice for work that a single thread would complete faster.</p><h3>Why parallelStream Doesn&#39;t Work for I/O</h3><p>There’s a recurring pattern in backend service code: using parallelStream to execute HTTP calls or database queries in parallel, aiming to reduce total latency. The intuition is reasonable — if I have 5 accounts and each query to an external service takes 200ms, running them in parallel would reduce latency from 1 second to ~200ms.</p><p>The problem is that parallelStream executes these operations on the commonPool workers, and those workers become <strong>blocked</strong> waiting for the network response. A blocked worker doesn&#39;t return the thread. It doesn&#39;t participate in work-stealing. It simply occupies a pool slot.</p><p>Returning to the port analogy: imagine you have 7 cranes (workers) and each must wait 3 minutes while a truck (external service) positions itself. During those 3 minutes, the crane can’t move other containers. If all 7 cranes are waiting for trucks simultaneously, the entire port stops — even though there are thousands of containers pending movement that could be processed.</p><p>On a Java server with 8 cores (7 workers in the commonPool), just 7 concurrent HTTP calls executed from parallelStream are enough to completely saturate the pool. Any other part of the application that depends on the commonPool — other parallelStreams, CompletableFuture.supplyAsync() without an explicit executor — is left waiting. This is <strong>starvation</strong>: resources exist but are monopolized by tasks that aren&#39;t using them productively.</p><p>The ForkJoinPool has a compensation mechanism (ManagedBlocker) that can create additional threads when it detects blocking, but parallelStream doesn&#39;t use it — stream lambdas don&#39;t implement the ManagedBlocker interface, so the pool doesn&#39;t know that workers are blocked.</p><h3>The Right Tool for Parallel I/O</h3><p>For I/O-bound operations, the alternative is a dedicated ExecutorService with CompletableFuture. This allows defining a thread pool exclusive to I/O, without contaminating the commonPool, with explicit control over thread count, timeouts, and error policies.</p><p>The conceptual difference is fundamental: parallelStream was designed to <strong>split computational work</strong> across cores; a dedicated executor was designed to <strong>manage concurrency of operations that wait</strong>. They are tools for different problems.</p><p>Starting with Java 21, virtual threads (Executors.newVirtualThreadPerTaskExecutor()) offer an even more natural alternative for concurrent I/O, as they allow creating thousands of lightweight threads whose blocking doesn&#39;t consume real operating system resources.</p><h3>Side Effects of the commonPool in Real Applications</h3><p>In a backend service running on Spring Boot (or any server framework), commonPool contamination has implications that go beyond performance.</p><p>Spring Security’s SecurityContext is stored in ThreadLocal. The ForkJoinPool.commonPool workers don&#39;t inherit that context, which means code executed inside a parallelStream has no access to the authenticated user&#39;s identity. The same applies to the MDC (Mapped Diagnostic Context) used by logging frameworks like Logback and Log4j2: logs emitted from commonPool workers lose the trace ID, request ID, or any other traceability context.</p><p>This creates an observability problem that’s difficult to diagnose. Logs appear without correlation, distributed tracing traces are incomplete, and in a production debugging scenario — precisely when visibility is needed most — information is fragmented between the request’s main thread and the pool’s anonymous workers.</p><p>The stack trace of exceptions thrown inside parallelStream also becomes fragmented. Instead of a linear call chain that reflects the source code flow, you get traces that pass through ForkJoinPool internal classes (ForkJoinWorkerThread.run, CountedCompleter.exec), making it harder to identify the exact point of failure.</p><h3>Technical Criteria: When to Consider parallelStream</h3><p>There’s no universal magic number, but there is a decision framework based on concrete variables.</p><p>The key metric isn’t just collection size, but the <strong>product of size times per-element cost</strong> compared against the <strong>fixed cost of parallelization</strong>. If that product doesn’t significantly exceed the fixed cost, parallelism destroys performance instead of creating it.</p><p>The fixed cost of parallelization includes creating Spliterators and ForkJoinTasks, enqueueing and dequeueing from work queues (CAS operations), inter-thread signaling (potential context switches), and merging partial results. On modern hardware, this fixed cost is in the range of tens of microseconds.</p><p>If the total work of the sequential stream is less than that fixed cost (for example, 50 string comparisons taking ~50 nanoseconds total), parallelStream is strictly worse.</p><p>As a pragmatic and conservative guide: with collections of fewer than 10,000 elements and cheap per-element operations (comparisons, field accesses, simple arithmetic), parallelStream provides no measurable benefit. The threshold drops if the per-element cost is high (cryptographic calculations, image processing, complex parsing) — in those cases, even hundreds of elements could justify parallelism.</p><p>But there are scenarios where even with millions of elements, parallelStream is inadequate: when there are I/O operations inside the pipeline, when lambdas mutate shared state, when execution order matters for correctness, or when the data source&#39;s Spliterator doesn&#39;t split efficiently (like a LinkedList, whose split is O(n)).</p><h3>Before Assuming, Measure</h3><p>The final and most important recommendation is this: performance isn’t guessed, it’s measured.</p><p>If you suspect a parallelStream could improve a hot path, the correct approach is writing a benchmark with JMH (Java Microbenchmark Harness) that compares the sequential version against the parallel one with production-representative data. JMH handles the complexities of JVM benchmarking (warm-up, JIT compilation, dead code elimination) that invalidate any informal measurement with System.nanoTime().</p><p>Beyond the isolated benchmark, it’s essential to monitor behavior in production under concurrent load. A parallelStream may look good in a single-threaded benchmark but degrade overall service throughput when multiple requests compete for the commonPool. Metrics like ForkJoinPool.commonPool().getQueuedTaskCount() and getActiveThreadCount() exposed through Micrometer or JMX can detect saturation before it manifests as user-visible latency.</p><h3>Conclusion</h3><p>parallelStream is a powerful tool designed for a specific use case: distributing <strong>significant CPU-bound work</strong> across <strong>large</strong> collections, with no <strong>shared state</strong> or <strong>side effects</strong>, using the fork/join model. Outside those parameters, it doesn&#39;t just fail to help — it actively hurts.</p><p>The most common mistakes are using it on small collections (where overhead exceeds the work), nesting it (where contention multiplies the overhead), and applying it to I/O-bound operations (where it saturates the JVM’s global commonPool).</p><p>The practical rule is simple: always start with .stream(). If a profiler or benchmark demonstrates that a sequential pipeline is a bottleneck, and the work is CPU-bound and stateless, then — and only then — evaluate parallelStream. For concurrent I/O, the right tool is a dedicated executor with CompletableFuture, or virtual threads starting with Java 21.</p><p>Real parallelism doesn’t come from changing a word in the code. It comes from understanding what kind of work is being done, where the real bottlenecks are, and which tool aligns with the problem’s characteristics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2733e3af606" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sum of Two Numbers Represented as Linked Lists (Reverse Order)]]></title>
            <link>https://medium.com/@jorgefelipeqs/sum-of-two-numbers-represented-as-linked-lists-reverse-order-2aa9b3207314?source=rss-ba71abadcbe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aa9b3207314</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jorge Felipe Quintero]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 02:30:57 GMT</pubDate>
            <atom:updated>2025-11-03T02:30:57.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*gSW5BkjjiJlLWbNoAnkeTg.png" /></figure><h3>Executive Summary</h3><p>Given two non-empty linked lists l1 and l2 representing non-negative numbers, where each node contains a single digit and the digits are stored in reverse order (the head is the least significant digit), we must add the two numbers and return the result as a new linked list, also in reverse order.</p><h3>Data Model</h3><p>Each linked list node has the following structure:</p><pre>class ListNode {<br>    int val;        // digit in [0..9]<br>    ListNode next;  // reference to the next node<br>}</pre><p>The lists do not contain leading zeros (except for the number 0 itself), and their length is in [1, 100].</p><h3>Key Idea (Invariant)</h3><p>We traverse both lists simultaneously, maintaining a carry between 0 and 1 (or more generally, 0..9 if more lists were involved). In each iteration, the partial sum is:</p><pre>sum = (value from l1 if exists, else 0) + (value from l2 if exists, else 0) + carry</pre><p>The new result digit is sum % 10, and the new carry is sum / 10 (integer division). We create a node with that digit and link it to the end of the result. The process continues until both lists are exhausted and carry == 0.</p><p>Invariant: After processing k nodes (k ≥ 0), the result list contains exactly the k least significant digits of the sum of the prefixes of l1 and l2, and carry represents the pending carry-over to the next digit.</p><h3>Step-by-Step Algorithm</h3><ol><li>Initialization</li></ol><ul><li>Create a dummy head node dummyHead with value 0 to simplify pointer handling.</li><li>Define a pointer current = dummyHead that points to the last node in the result.</li><li>Define carry = 0.</li><li>Define read pointers p = l1 and q = l2.</li></ul><p>2. Main Loop</p><ul><li>While p != null or q != null or carry != 0:</li><li>Read x = (p != null) ? p.val : 0.</li><li>Read y = (q != null) ? q.val : 0.</li><li>Compute sum = x + y + carry.</li><li>Update carry = sum / 10 (integer division).</li><li>Determine digit = sum % 10.</li><li>Create a new node node = new ListNode(digit).</li><li>Link: current.next = node and move current = node.</li><li>Advance p = p.next if p != null; advance q = q.next if q != null.</li></ul><p>3. Termination</p><ul><li>Return dummyHead.next (skip the dummy head).</li></ul><h3>Diagram (Iteration Flow)</h3><pre>p.val ─┐<br>       ├──► sum = x + y + carry ──► digit = sum % 10 ──► [append digit]<br>q.val ─┘                            carry = sum / 10 ──► (next iteration)</pre><h3>Detailed Example</h3><h3>Input</h3><ul><li>l1 = [2,4,3] ⇒ number 342</li><li>l2 = [5,6,4] ⇒ number 465</li></ul><h3>Iterations</h3><ol><li>x=2, y=5, carry=0 → sum=7 → digit=7, carry=0 → result: [7]</li><li>x=4, y=6, carry=0 → sum=10 → digit=0, carry=1 → result: [7,0]</li><li>x=3, y=4, carry=1 → sum=8 → digit=8, carry=0 → result: [7,0,8]</li><li>Lists exhausted and carry=0 → end.</li></ol><h3>Output</h3><p>[7,0,8] (which represents 807).</p><h3>Complexity</h3><ul><li>Time: O(max(m, n)), where m = len(l1) and n = len(l2). Each node is visited at most once.</li><li>Additional space: O(1) (excluding the result list), since only a few variables are used and exactly one node per result digit is created.</li></ul><h3>Informal Proof of Correctness</h3><ul><li>Totality: The loop continues while there are digits to process or a pending carry.</li><li>Invariant preservation: At each step, we append the least significant digit of the partial sum to the result and propagate the remainder as carry.</li><li>Termination: Since the lists are finite and carry decreases to at most 1 per iteration, eventually p == q == null and carry == 0, ending the loop.</li></ul><h3>Idiomatic Java Implementation</h3><pre>public class ListNode {<br>    int val;<br>    ListNode next;<br>    ListNode() {}<br>    ListNode(int val) { this.val = val; }<br>    ListNode(int val, ListNode next) { this.val = val; this.next = next; }<br>}</pre><pre>class Solution {<br>    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {<br>        ListNode dummyHead = new ListNode(0);<br>        ListNode current = dummyHead;<br>        int carry = 0;</pre><pre>        while (l1 != null || l2 != null || carry != 0) {<br>            int x = (l1 != null) ? l1.val : 0;<br>            int y = (l2 != null) ? l2.val : 0;</pre><pre>            int sum = x + y + carry;<br>            carry = sum / 10;<br>            int digit = sum % 10;</pre><pre>            current.next = new ListNode(digit);<br>            current = current.next;</pre><pre>            if (l1 != null) l1 = l1.next;<br>            if (l2 != null) l2 = l2.next;<br>        }<br>        return dummyHead.next;<br>    }<br>}</pre><h3>Edge Cases to Consider</h3><ol><li>Different lengths: e.g., l1=[9,9,9], l2=[1] → continue summing with x=0 or y=0 once one list ends.</li><li>Carry at the end: e.g., l1=[5], l2=[5] → result [0,1] (10).</li><li>One list is zero: l1=[0], l2=[7,3] → result [7,3].</li><li>All digits are 9: l1=[9,9,9,9,9,9,9], l2=[9,9,9,9] → [8,9,9,9,0,0,0,1].</li><li>Minimum input: l1=[0], l2=[0] → [0].</li></ol><h3>Suggested Test Cases (Table)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*FMrtuKT3jo8MivUgUp7Nug.png" /></figure><h3>Common Mistakes (and How to Avoid Them)</h3><ul><li>Forgetting the carry at the end of the loop → use the condition while (l1 != null || l2 != null || carry != 0).</li><li>Incorrectly linking the new node to the result → always use current.next = new ListNode(digit); current = current.next;.</li><li>Using unnecessary auxiliary structures (like ArrayList) → build the list on the fly using a dummy node.</li><li>Mixing up digit order → remember that the head node is the unit (reverse order).</li></ul><h3>Variants and Extensions</h3><ul><li>Lists in forward order (MSD first): requires reversing the lists or using a stack/recursion to sum from the end.</li><li>Sum of <em>k</em> lists: iterate by accumulating sum with all available digits and a generalized carry.</li><li>Arrays instead of lists: same logic, but use indices instead of nodes.</li></ul><h3>Output Space Complexity</h3><p>The result list size is at most max(m, n) + 1 (due to a possible final carry). This space is necessary to represent the sum.</p><h3>Language-Neutral Pseudocode</h3><pre>function addTwoNumbers(l1, l2):<br>    dummy ← new Node(0)<br>    curr  ← dummy<br>    carry ← 0<br>    p ← l1<br>    q ← l2<br>    while p ≠ null or q ≠ null or carry ≠ 0:<br>        x ← (p ≠ null) ? p.val : 0<br>        y ← (q ≠ null) ? q.val : 0<br>        s ← x + y + carry<br>        carry ← s div 10<br>        digit ← s mod 10<br>        curr.next ← new Node(digit)<br>        curr ← curr.next<br>        if p ≠ null: p ← p.next<br>        if q ≠ null: q ← q.next<br>    return dummy.next</pre><h3>Style/Clean Code Considerations (Java)</h3><ul><li>Using a dummyHead avoids conditional logic for the first node.</li><li>Keep variable names short but clear (x, y, sum, carry).</li><li>Limit variable scope to the loop when possible.</li><li>Avoid boxing (Integer) and prefer primitives (int).</li></ul><h3>Conclusion</h3><p>The algorithm is linear, in-place regarding additional memory, and elegant thanks to the use of a dummy node and an explicit carry. It correctly handles unequal lengths and final carry, satisfying the problem’s constraints.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aa9b3207314" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Details of the AWS Outage]]></title>
            <link>https://medium.com/@jorgefelipeqs/details-of-the-aws-outage-93879d101e53?source=rss-ba71abadcbe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/93879d101e53</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jorge Felipe Quintero]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 15:08:37 GMT</pubDate>
            <atom:updated>2025-10-23T15:08:37.216Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FOgLReb-b1nV66ep" /></figure><p>On Monday, October 20, 2025, the N. Virginia (us-east-1) region of AWS experienced a major outage that degraded or rendered hundreds of services and applications around the world unavailable. The root cause was a DNS resolution problem in Amazon DynamoDB, which triggered a chain of internal failures affecting critical components such as EC2 and Network Load Balancer (NLB) health checks.</p><p>AWS later published a technical Post-Event Summary (PES) and a full timeline on its Health Dashboard describing the event’s key moments and recovery actions.</p><h3>What Happened?</h3><h3>DynamoDB’s DNS Automation (Planner / Enactors)</h3><p>To operate at massive scale, DynamoDB uses multiple load balancers (LBs) and maintains hundreds of thousands of DNS records per region (public endpoints, FIPS, IPv6, per-account variants, etc.). That DNS “snapshot” isn’t manually maintained — it’s managed by an automated system composed of two main components:</p><ul><li>DNS Planner: Monitors the capacity and health of load balancers and generates <em>DNS plans</em> (lists of load balancers with weights) per endpoint. Usually, there is a single regional plan replicated across related endpoints (for example, IPv6 and public).</li><li>DNS Enactor: Applies those plans in Amazon Route 53. To ensure resilience, there are independent Enactor instances in each Availability Zone (AZ). Each Enactor fetches new plans and performs atomic transactions in Route 53, ensuring consistency even when multiple Enactors update in parallel.</li></ul><h4>Where It Failed</h4><p>A latent defect (a race condition) existed in this process:</p><ol><li>One Enactor A became very slow while applying an old plan (due to contention and retries).</li><li>Meanwhile, the Planner continued producing new plans, and another Enactor B successfully applied a newer one.</li><li>After completing its work, Enactor B performed cleanup of outdated plans.</li><li>At that same moment, Enactor A — still holding the old plan in memory — overwrote the regional endpoint with that obsolete plan.</li><li>B’s cleanup process then removed that plan as “too old,” leaving the endpoint with no IP addresses.</li></ol><p>Result: The regional DynamoDB endpoint became empty and locked, unable to auto-update. Manual intervention was required to restore the DNS records.</p><h3>Technical Timeline (PDT)</h3><ul><li>11:48 PM (Oct 19): API errors begin in DynamoDB (us-east-1) due to DNS resolution failures (dynamodb.us-east-1.amazonaws.com).</li><li>12:38 AM: AWS identifies the DNS issue.</li><li>1:15 AM: Initial mitigations applied to restore internal tooling.</li><li>2:25 AM: DNS restored; clients regain connectivity as local caches expire (~2:40 AM).</li><li>Global Tables finish synchronization by 2:32 AM.</li><li>2:25–10:36 AM:</li><li>EC2 remains impacted — new instance launches fail due to internal subsystem issues in DWFM (host lease management) and Network Manager (network state propagation).</li><li>DWFM enters congestive collapse; AWS applies throttling and selective restarts (~4:14 AM).</li><li>5:28 AM: DWFM restores leases.</li><li>10:36 AM: Network propagation normalizes.</li><li>1:50 PM: EC2 APIs fully operational again.</li><li>5:30 AM–2:09 PM:</li><li>NLB suffers connection errors due to health checks running on nodes whose networks weren’t fully ready → <em>flapping</em> and DNS <em>failovers</em> per AZ.</li><li>9:36 AM: AWS disables automatic failover → error rates drop.</li><li>2:09 PM: Failover re-enabled.</li><li>3:01 PM: AWS declares full recovery; some queues (Config, Redshift, Connect) drain over the next few hours.</li></ul><h3>Causal Chain</h3><ol><li>Race-condition bug in DynamoDB’s DNS automation → a blank DNS record is published, locking the update system.</li><li>Dependent internal services (EC2/DWFM, catalogs, queues, leases) time out because they can’t resolve the endpoint.</li><li>DNS restoration triggers a massive retry storm → congestive collapse within DWFM; without valid leases, EC2 cannot launch new instances.</li><li>Network Manager delays network-state propagation → new instances come up without connectivity.</li><li>NLB misinterprets health using outdated data → <em>flapping</em> health checks and erroneous <em>failovers</em> → additional capacity loss.</li></ol><h3>Impact on Services</h3><ul><li>DynamoDB (primary impact): API and connectivity failures. Global Tables continued serving other regions but with replication lag to and from us-east-1.</li><li>EC2: Failures launching new instances (running ones unaffected). Returned InsufficientCapacity or RequestLimitExceeded due to throttling and lost leases. Degraded connectivity until network propagation stabilized.</li><li>NLB: Connection errors from health checks relying on outdated network information. Temporary mitigation: disable automatic failover.</li><li>Lambda: Errors creating/updating functions, slower SQS/Kinesis polling, and asynchronous invocation issues. AWS applied temporary throttles and drained backlogs during recovery.</li><li>ECS/EKS/Fargate: Failures in container launch and cluster scaling.</li><li>Amazon Connect: Voice/chat routing issues (busy tones, dead air) during the peak impact.</li><li>External impact (“half of the Internet”): Major global apps (Amazon.com, Alexa, Snapchat, Fortnite, banking platforms, etc.) reported outages or severe degradation.</li></ul><h3>Why It Was So Severe</h3><ol><li>Internal dependencies on DynamoDB: Many control-plane systems (DWFM, orchestration queues, catalogs) use DynamoDB. When the regional endpoint fails, the entire control plane halts, even though data planes remain healthy.</li><li>DNS caching on clients/resolvers: Even after Route 53 was fixed, recovery relied on TTL expiration, creating a non-uniform, delayed return to service.</li><li>Massive backlogs and congestive collapse: Once DNS returned, all systems retried simultaneously. Without concurrency control, the system failed to progress until throttling and restarts were applied.</li><li>Over-sensitive health checks: NLB evaluated new nodes before their networks were fully propagated → <em>flapping</em> and false <em>failovers</em> that removed healthy capacity. AWS had to temporarily disable automatic failover to stabilize.</li><li>Regional concentration in us-east-1: Many critical workloads and “global” services (e.g., parts of IAM) depend on this region. The effect spilled beyond its physical boundaries.</li></ol><h3>What to Do Knowing This Could Happen Again</h3><h3>1. DNS and Endpoints</h3><ul><li>Avoid single-region control-plane dependencies. If us-east-1 hosts critical endpoints (IAM, DynamoDB Global Tables primaries), distribute the load across active-active regions or set up automated failover.</li><li>Manage DNS TTLs and caches carefully. Tune TTLs and use robust local resolvers. Implement retries with exponential backoff + jitter to prevent retry storms.</li><li>Leverage VPC Endpoints. When possible, use private endpoints to reduce reliance on public Internet DNS.</li></ul><h3>2. EC2 and Instance Launches</h3><ul><li>Don’t rely on “hot” launches during crises. Use warm pools, <em>standby</em> instances, or <em>pre-scaled capacity</em> for predictable peaks.</li><li>Enable multi-AZ and “Any AZ” Auto Scaling. Let EC2 choose available zones (part of AWS’s own mitigation strategy).</li><li>Test multi-region strategies. Regularly simulate manual or automated failovers for databases and control planes.</li></ul><h3>3. Networking and Load Balancing</h3><ul><li>Review NLB/ALB configuration:</li><li>Enable cross-zone load balancing and maintain over-provisioning per AZ.</li><li>Adjust health-check thresholds and timeouts to tolerate transient states.</li><li>Prevent DNS from dropping capacity based on temporary signals — use multi-signal or canary health checks.</li></ul><h3>4. Serverless and Queues</h3><ul><li>Define explicit back-pressure for Lambda + SQS/Kinesis: control concurrency, batchSize, maxReceiveCount, and DLQ; plan a gradual ramp-up after incidents to drain backlogs safely.</li></ul><h3>5. Recovery Procedures</h3><p>Maintain up-to-date runbooks for:</p><ul><li>Flushing DNS caches (apps, proxies, gateways) when AWS reports resolution issues.</li><li>Disabling sensitive features (e.g., aggressive auto scaling) during partial recoveries.</li><li>Restarting or purging internal queues when detecting <em>congestive collapse</em> symptoms (like DWFM experienced).</li></ul><h3>Conclusion</h3><p>The October 20, 2025 outage in us-east-1 demonstrated how a seemingly isolated flaw — the automated DNS subsystem in DynamoDB — can cascade into a large-scale Internet disruption. Understanding AWS’s internal dependencies and designing multi-region, control-plane-resilient architectures are essential steps to reduce the blast radius of future events of this magnitude.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93879d101e53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vertical vs Horizontal Scaling: A Technical Guide for Beginners]]></title>
            <link>https://medium.com/@jorgefelipeqs/vertical-vs-horizontal-scaling-a-technical-guide-for-engineers-f115e332575e?source=rss-ba71abadcbe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f115e332575e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jorge Felipe Quintero]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 14:16:32 GMT</pubDate>
            <atom:updated>2025-10-15T14:28:18.681Z</atom:updated>
            <content:encoded><![CDATA[<p>Should I buy a bigger machine or more of them?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*0ML2Ru3IGf8XZQDF.jpeg" /></figure><p>This seemingly simple question defines the iflection point in the growth of any distributed system.</p><p><strong>Vertical Scaling </strong>(adding more resources to a single machine) is tempting for its simplicity but has physical limits. <strong>Horizontal Scaling </strong>(adding more machines) offers elasticity and resilience, but introduces architectural complexity. This article breaks down both approaches with technical rigor and an engineering mindset.</p><ol><li><strong>Fundamental Definitions</strong></li></ol><p><strong>Vertical Scaling (Scale-Up)</strong></p><p>Involves <strong>increasing the capacity of an existing instance </strong>by adding CPU, RAM, or Storage. It’s the most direct way to improve performance, especilly in monolithic or OLTP systems. <strong>Example: </strong>Upgrading an AWS instance from <em>t3.medium </em>to <em>t3.2xlarge</em>, or increasing resource limits for a Kubernetes pod.</p><p><strong>Horizontal Scaling (Scale-Out)</strong></p><p>Means <strong>adding more replicas </strong>of an application or service, usually behind a <strong>load balancer</strong>. It’s the fundation of elasticity and high availability in modern distributed systems. <strong>Example: </strong>Adding more pods in a Kubernetes Deployment using a <strong>Horizontal Pod Autoscaler (HPA)</strong>.</p><p>2. <strong>Key Technical Differences</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*KRqdqO_tNfrMFE3QJtraew.png" /></figure><p>3. <strong>Limits</strong></p><p><strong>Vertical Scaling (Physics)</strong></p><p>Reaches its limit when <strong>physical bottlenecks </strong>emerge: memory bandwidth, NUMA latency, cache coherence, or I/O saturation. Scaling is finite, even the largest instances hit diminishing returns.</p><p><strong>Horizontal Scaling (Distributed Complexity)</strong></p><p>Introduces <strong>coordination, consistency, and latency </strong>challenges. These are addressed with <strong>replication, partitioning, load balancing, </strong>and <strong>consistency models </strong>(eventual, strong, or casual) depending on system requirements.</p><p>4. <strong>Desicion Framework: When to Prioritize Each</strong></p><p><strong>Prioritiza Vertical Scaling if:</strong></p><ul><li>The workload is <strong>CPU-bound or Memory-boud</strong>.</li><li><strong>Latency </strong>is critical and distributions overhead outweighs benefits.</li><li>The architecture is <strong>monolithic</strong>, or state can’t be easily externalized.</li></ul><p><strong>Prioritiza Horizontal Scaling if:</strong></p><ul><li>You require <strong>high availability </strong>or<strong> disaster recovery (HA/DR)</strong>.</li><li>Your application is <strong>stateless or idempotent</strong>.</li><li>You need <strong>autoscaling </strong>for variable workload.</li><li>You can tolerate <strong>eventual consitency </strong>or shard your data.</li></ul><p>5. <strong>Scaling Patterns in Distributed System</strong></p><ul><li><strong>Load Balancing: </strong>Common algorithms include <strong>Round Robbin</strong>,<strong> Least Connections, </strong>and<strong> Consistent Hashing. </strong>Avoid <em>sticky sessions </em>if true scalability is desire.</li><li><strong>Partitioning (Sharding): </strong>Splits data or workloads across multiple nodes based on a key. Method include: <strong>Hash-based, Consistent-hashing, etc.</strong></li><li><strong>Replications and Quorums: </strong>Using strategies like <strong>Dynamo</strong>, which prioritize availability with eventual reconciliation, or<strong> Spanner</strong>, which prioritizes strong consistency through synchronized clocks.</li><li><strong>Autoscaling: </strong>services like<strong> AWS Auto Scaling Groups</strong>,<strong> GCP Managed Instance Groups</strong>, or<strong> Azure VM Scale Sets </strong>provide automated elasticity based on CPU, RPS, or custom metrics.</li></ul><p>6. <strong>Transition Plan: Vertical to Horizontal</strong></p><ul><li><strong>Externalize state</strong> (sessions, cache, DB) and make API’s idempotent.</li><li>Add a <strong>load balancer</strong> with health checks and multi-replica deployments.</li><li>Enable <strong>autoscaling</strong> based on meaningful metrics (RPS, queue lag, CPU).</li><li>Increase <strong>observability </strong>(logs, metrics, distributed tracing).</li><li>Design <strong>data partitioning</strong> and progressive re-sharding plans.</li></ul><p><strong>Conclusion</strong></p><p><strong>Vertical scaling </strong>is simple, effective, and cheap early on but hits physical ceilings. <strong>Horizontal scaling</strong> is complex but enables resilience, high availability, and long term growth. A good architecture design to <strong>start vertical</strong> but <strong>be ready for horizontal.</strong></p><p>Ultimately, the decision isn’t <em>one or other</em>, but <strong>when and how to combine both</strong>. Modern systems succed by recognizing that scaling isn’t just adding resources, it’s <strong>mastering the interaction between physics, software, and distributed architecture.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f115e332575e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a URL Shortener]]></title>
            <link>https://medium.com/@jorgefelipeqs/building-a-url-shortener-75285ae4c87a?source=rss-ba71abadcbe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/75285ae4c87a</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jorge Felipe Quintero]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 14:05:12 GMT</pubDate>
            <atom:updated>2025-10-02T14:05:12.779Z</atom:updated>
            <content:encoded><![CDATA[<p>This design is intended to provide a solution within the context of a job interview, which is why we will leave aside some considerations that could affect the design in a real production environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wgHq_jAUrzhuxseV.jpg" /></figure><p>With this in mind, the problem statement is as follows:</p><p><strong><em>”</em></strong><em>You are asked to design a URL shortener that returns the address </em><strong><em>fake-company.io/XXXXXX</em></strong><em>, so that we can provide a short URL service to our users, who in turn can share this short URL if they want to distribute the original address of their website.</em><strong><em>”</em></strong></p><p><strong>Given the context, the first thing worth asking is:</strong></p><ul><li>How many characters will this shortener return to append to the path?</li><li>What will be the encoding/hash base for those characters?</li><li>Will the shortened URLs have a TTL, or will they remain indefinitely?</li><li>Should we perform validations before returning the shortened URL?</li></ul><p>Since validations are a design in themselves, we’ll leave them out of scope. For this case, we’ll use <strong>6 characters</strong> and work with <strong>base 36 (a–z, 0–9)</strong> to simplify the problem as much as possible and focus on the reasoning behind the shortener’s design, imagining that paths never expire.</p><p><strong>Calculating the possibility space</strong></p><ul><li>Each character has 36 possible values, and they are independent of each other.</li><li>Therefore, we must calculate 36⁶, which gives us <strong>2,176,782,336 possible combinations</strong>.</li><li>This means that, in the worst case, our database could end up holding just over <strong>two billion records</strong>.</li></ul><p><strong>Database design</strong></p><p>or this scenario, we could use an <strong>SQL database</strong> with at least the following columns:</p><ul><li>`short_path` → the generated hash.</li><li>`original_url` → the original URL.</li><li>`created_at` → the creation/assignment timestamp.</li><li>`is_assigned` (boolean/flag) → indicates whether that path has already been assigned.</li></ul><p>Since many short URLs will be queried more than once, it’s also worth considering:</p><ul><li>Applying a <strong>CQRS pattern</strong>, moving the read side to a NoSQL database for better scalability.</li><li>Using a <strong>key–value database on disk</strong> (e.g., RocksDB) to handle simple lookups.</li><li>Or, keeping everything in SQL but relying on an <strong>in-memory database like Redis</strong>, with a configurable TTL, to cache the most frequently queried paths.</li></ul><p><strong>Path generation strategy</strong></p><p>The system flow would look like this:</p><p>1. Prepare the database with all possible combinations, shuffled and persisted in a table.</p><p>2. Each record has a flag `is_assigned = false`.</p><p>3. When a user submits a URL to shorten:</p><ul><li>Perform necessary validations (discussion for another time).</li><li>Lock the next free record using `SELECT … FOR UPDATE` (SQL with locking).</li><li>Update the record:</li><li>Save the `source`.</li><li>Mark `is_assigned = true`.</li><li>Record the `created_at`.</li><li>Release the lock and return the `short_path` to the user.</li></ul><p>4. When the user accesses `fake-company.io/{short_path}`, we run a `SELECT` using that value and redirect them to the `source`.</p><p><strong>Additional interview notes</strong></p><ul><li><strong>Scalability:</strong> this design can scale horizontally if we partition the combinations across multiple database nodes.</li><li><strong>Consistency:</strong> using `SELECT FOR UPDATE` ensures no collisions occur in concurrent environments.</li><li><strong>Security:</strong> it’s better to avoid assigning combinations in natural order (`000000`, `000001`, …) because it exposes predictability. This is why the shuffle is important.</li><li><strong>Monitoring:</strong> we can expose metrics to track how much of the namespace has already been consumed.</li></ul><p><strong>Conclusion</strong></p><p>With this design, we solve the problem of unique path assignment and ensure that each shortened URL has a consistent and scalable flow.</p><p>I hope this guide serves as a clear starting point to tackle, from a simple perspective, one of the most common questions in technical interviews, while also opening your mind to the various possibilities in system design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75285ae4c87a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Solve The Two Sum Problem with Java]]></title>
            <link>https://medium.com/@jorgefelipeqs/how-to-solve-the-two-sum-problem-with-java-c23fa0445d4a?source=rss-ba71abadcbe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c23fa0445d4a</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <dc:creator><![CDATA[Jorge Felipe Quintero]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 15:36:06 GMT</pubDate>
            <atom:updated>2025-09-09T15:36:06.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*mnOfSgO8xETCWrSR" /></figure><p>The first step is to understand the problem. If you visit the LeetCode problem section, you will find the statement of the problem, which gives the following description:</p><p>&gt; <strong>Given an array of integers `nums` and an integer `target`, return the indices of the two numbers such that they add up to `target`.</strong></p><p>&gt; You may assume that each input would have exactly one solution, and you may not use the same element twice.</p><p>&gt; You can return the answer in any order.</p><p><strong>Examples</strong></p><p><strong>Example 1:</strong></p><p>Input: `nums = [2,7,11,15], target = 9`</p><p>Output: `[0,1]`</p><p>Explanation: Because `nums[0] + nums[1] == 9`, we return `[0,1]`.</p><p><strong>Example 2:</strong></p><p>Input: `nums = [3,2,4], target = 6`</p><p>Output: `[1,2]`</p><p><strong>Example 3:</strong></p><p>Input: `nums = [3,3], target = 6`</p><p>Output: `[0,1]`</p><p><strong>Constraints</strong></p><p>- `2 &lt;= nums.length &lt;= 1⁰⁴`</p><p>- `-1⁰⁹ &lt;= nums[i] &lt;= 1⁰⁹`</p><p>- `-1⁰⁹ &lt;= target &lt;= 1⁰⁹`</p><p>- Only one valid answer exists.</p><p><strong>**Follow-up:**</strong> Can you come up with an algorithm with time complexity less than O(n²)?</p><p><strong>Step 1: Initial Approach</strong></p><p>If we want to find the addends for a specific number, our first reasoning must be related to how we traverse the list of elements. At first, the answer seems simple: we can use a nested loop to check all possible pairs. However, this generates an algorithm with two nested loops, meaning each number is compared with every other number in the list, leading to a time complexity of O(n²). Therefore, we need a different approach.</p><p><strong>Step 2: Using a HashMap</strong></p><p>Since we want to traverse the list only once while keeping track of values, the best option is to store these values in a key-value structure. In this case, a `HashMap` works perfectly, storing numbers as keys and their indices as values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*4-pRBbMmjm86V3-drIS6iQ.png" /></figure><p><strong>Step 3: Finding the Missing Addend</strong></p><p>Now, we need to determine how to find the missing addend that complements our current number to reach the target. The reasoning is simple:</p><p>listNumber + X = target</p><p>Rearranging the equation:</p><p>X = target — listNumber</p><p><strong>Step 4: Implementing the Algorithm</strong></p><p>We traverse the list with a single loop. For each number, we calculate its complement and check if it already exists in the HashMap.</p><p>If it does, we have found the two indices.</p><p>If it doesn’t, we store the current number and its index in the HashMap.</p><p>This results in an algorithm with O(n) time complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*oMAOSDEcrMmN3LC8pw4B2g.png" /></figure><p><strong>Summary of the Algorithm</strong></p><p>1. Create a HashMap to store the numbers and their indices.</p><p>2. Iterate through the array and calculate the complement for each number.</p><p>3. If the complement exists in the map, return the pair of indices.</p><p>4. If no pair is found, throw an exception.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c23fa0445d4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 types of databases you should know]]></title>
            <link>https://medium.com/@jorgefelipeqs/6-types-of-databases-you-should-know-e68414415f89?source=rss-ba71abadcbe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e68414415f89</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jorge Felipe Quintero]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 04:49:19 GMT</pubDate>
            <atom:updated>2025-08-31T04:49:19.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*Bv8rMyrNcSz9OUJ_5FeVxA.png" /></figure><p>To pick the right tool for the job, it’s crucial to select the ideal database for each of our use cases. Understanding these six database types will help us make the best decision when the time comes.</p><p><strong>1. Key-Value Databases</strong></p><p>The most representative example of a key-value database is <strong>Redis</strong>. By definition, they have a structure similar to JavaScript objects or Python maps. They use a set of unique keys associated with a specific value. These databases often have designs oriented towards in-memory storage, which makes them fast and useful for <strong>caching</strong>. However, their capacity is limited since they aren’t disk-based, and they don’t allow for filtered searches or complex associations.</p><p><strong>2. Wide-Column Databases</strong></p><p>A great example of this type is <strong>Cassandra DB</strong>. Its structure is based on a key associated with a series of columns that store specific data without following a fixed structure. This allows each key to have different columns, adapting to the needs of the record and the business. You can also retrieve the specific values you need using query languages like CQL. They are easy to scale because they are decentralized, which allows data to be replicated across different nodes. However, they do not permit relationships in queries. These databases are ideal for storing large amounts of data generated by a single source over specific periods. They are geared towards use cases with frequent writes but sporadic updates and reads. For example, they can be used for search or price histories, or as an intermediate database in distributed design patterns to store data temporarily before persisting it in a more complete database.</p><p><strong>3. Document Databases</strong></p><p>In this category, we find databases like <strong>MongoDB</strong>, <strong>Firebase Firestore</strong>, and <strong>CouchDB</strong>. In them, each “document” is a container of key-value pairs. These documents are grouped into collections, which allows for a more flexible and scalable organization of data. Additionally, fields can be indexed to optimize searching, and hierarchical structures can be created using sub-documents or arrays. The most appropriate way to store data is by grouping the data you need to display together in a single entry, as <strong>joins</strong> aren’t possible. Write and update processes often require greater complexity, but reads are very fast. They are useful if you don’t have a clear, defined structure, such as in an <strong>MVP</strong>, or if the structure has a clear entity but doesn’t always have the same data types, as in some <strong>**IoT**</strong> apps. They are also very useful as a read database within design patterns like <strong>CQRS</strong>.</p><p><strong>4. Relational Databases</strong></p><p>This is the most traditional and widely used type of database. Its structure is based on tables with columns and records stored in rows. These rows store information that can be related to one another through unique values (<strong>primary keys</strong>) using the <strong>SQL</strong> language. For this to be possible, the data must be stored in a normalized way using schemas. This allows the database to comply with <strong>ACID</strong> principles when performing an operation, which is its main advantage.</p><p><strong>5. Graph Databases</strong></p><p>An example is <strong>Neo4j</strong>. In this type of DB, relationships are data that are treated as edges, and the objects to be related are the nodes of the structure. This allows for many-to-many relationships without the need for intermediate tables. They are ideal for recommendation systems, trend mapping used in fraud detection, and for modeling complex connections, such as in social networks. For instance, they can be used for building functionalities like friend suggestions by identifying people you may know based on shared connections. Additionally, they can be applied to analyze influence within a network and to detect communities of users with similar interests.Furthermore, graph databases are useful for identity and access management by modeling the relationships between users, roles, permissions, and resources. This allows for quick permission verification and simplifies security audits.</p><p><strong>6. Search-Oriented Databases</strong></p><p>These are generally based on the <strong>Apache Lucene</strong> project. One of the most representative databases of this type is <strong>Elasticsearch</strong>, which allows for full-text searches and real-time data analysis. Their function is similar to that of document databases, but in the background, the database analyzes the entire document, creating searchable indices that generate matches through small entries. They tend to be costly in terms of performance but significantly improve the user experience.</p><p>Knowing these databases will give you the tools to choose the one that best suits your needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e68414415f89" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>