RSSAmplifier

Blog

Home on Chege's Blog

Recent content in Home on Chege's Blog

curiosities.devRSS feed ↗545 posts

Latest posts

Passing Data Asynchronously Between Producers and Consumers (.NET)

A channel is a data structure that&rsquo;s used to store produced data for a consumer to retrieve, and an appropriate synchronization to enable that to happen safely, while also enabling appropriate notifications in both directions. A Toy Channel public sealed class Channel < T > { // Use a thread-safe data store to free us from locking semantics for any // number of producers and consumers.…

Distributed Systems Potpourri

Contains content that is not extensive enough for its own page. Streams and Event Sourcing Unlike message queues , streams can retain data for a configurable period of time, allowing consumers to read and re-read messages from a specified time. You can use a stream to ingest high volumes of events in real-time, e.g., real-time analytics of user engagements in social media. Event sourcing involves…

Blob Storage

Blob Storage Unstructured blobs of data include images, videos, and other files. Typically, these are stored in blob storage, and the core database stores metadata, e.g., blob URL. Common setup for large binary artifacts. Credits: Hello Interview. Blob storage solutions like S3 can be considered infinitely scalable within your account limits. They are also cost effective, e.g., AWS S3 charges…

System Design Practice: Metrics Monitoring System

Functional Requirements FR1: Platform can ingest metrics (CPU, memory, latency, custom counters) from services. FR2: Users can query and visualize metrics on dashboards with filters, aggregations, and time ranges. FR3: Users can define alert rules with thresholds over time windows, e.g., &ldquo;alert if P99 latency > 500ms for 5min&rdquo;. FR4: Users can receive notifications when alerts fire,…

High Performance Networking in Chrome

Performance in Context The execution of a web browser primarily involves three tasks: fetching resources, page layout and rendering, and JavaScript execution. That said, optimizing the last two tasks won&rsquo;t do much good if the browser is blocked on the network, waiting for resources to arrive. Of the top 100K, the median page on desktop requests 97 resources weighing 2,954KB in total, and…

Uri Tupka and the Gods

BISHOP 1. Your damned letter to the Emperor &ndash; URI TUPKA. How could I not? When he commissioned a giant goat statue &ndash; a hundred feet tall and solid gold&hellip;? BISHOP 1. And didn&rsquo;t we warn you what would happpen? Didn&rsquo;t we all warn you? It was only to remind him. Scripture. Theodipus 6:19 &ndash; &ldquo;And all men shall be equal to each other under the eyes of the gods,…

AsyncIO in Python

Only covers the high level building blocks of asyncio . has a second section on how asyncio and await internally work. The Event Loop The event loop contains a collection of jobs to be run. Some jobs are added by application code, and others indirectly by asyncio . The event loop takes a job from its backlog and invokes it (&ldquo;gives it control&rdquo;). Once that job pauses or completes, it…

API Design

Notes For 90% of interviews, default to REST, which maps resources to URLs and uses HTTP methods to manipulate them, e.g., POST /events/{id}/bookings for creating a booking. When returning large result sets, pagination comes into play. Cursor-based pagination works better for real-time data where new items get added frequently. Offset-based pagination is fine for most cases. How does cursor-based…

Caching

Notes For read-heavy applications, storing frequently accessed data in fast memory (e.g., Redis) allows you to skip the DB entirely for some reads. A cache hit on Redis takes ~1ms compared to 20-50ms for a typical DB query, and this speedup is impactful in the order of millions of requests. In a web application, user sessions are typically stored in a distributed cache, allowing the system to…

CAP Theorem

Notes The CAP theorem states that you can only have 2 of 3 properties at once: Consistency: All nodes see the same data. Availability: Every request gets a response. Partition Tolerance: System works even when network connections fail between nodes. In practice, network partitions are unavoidable in distributed system. Choosing consistency means some nodes will refuse to serve requests rather than…

Data Modeling

Data Modeling Choosing what data to store and how to structure it directly affects performance, scalability, and maintenance. Relational databases are useful when you have structured data with clear relationships and need strong consistency (transaction-based actions, enforcing foreign key constraints). NoSQL databases shine for flexible schemas or when you need to scale horizontally across many…

Distributing Work

Sharding Sharding comes up when a single database won&rsquo;t work (e.g., hit storage limits, write throughput limits, or read throughput limits) and you need to split your data across multiple independent servers. For a user-centric social media app, sharding by user_id means all of a user&rsquo;s posts, likes, and comments live on one shard. User-scoped queries are fast, but &ldquo;trending…

Greedy Algorithms

Sample Problem You are given two integer arrays: greeds , where greeds[i] represents the minimum size of a cookie that a child needs to to be satisfied. cookies , where cookies[j] represents the size of a cookie. Assign cookies such that as many children as possible are satisfied. Each child can receive at most one cookie, and each cookie can be given to only one child. A Greedy Algorithm def…

Networking Essentials

Notes At a basic level, understand how services talk to each other and what happens when those connections fail or get slow. For 90% of the use cases, default to HTTP over TCP. WebSockets and Server-Sent Events (SSE) come up when you need real-time updates. SSE is unidirectional - the client makes an initial HTTP request to open the connection, and the server pushes data down that connection.…

Of [Non]Overlapping Intervals

#intervals-algorithms Merge Overlapping Intervals Problem Statement: Merge Overlapping Intervals Given an integer array intervals where intervals[i] = [start_i, end_i] , merge all overlapping intervals and return an array of the non-overlapping intervals. For example \([[1,3],[2,6],[8,10],[15,18]] \to [[1,6],[8,10],[15,18]]\) because \([1,3]\) and \([2,6]\) overlap and merge into \([1,6]\).…

Print Zero Even Odd

Problem printNumber(7) prints 7 to the console. You are given an instance of the ZeroEvenOdd class with 3 functions: zero outputs 0 s, even outputs even numbers, and odd outputs odd numbers. The same ZeroEvenOdd instance is passed to three different threads, where thread A calls zero() , thread B calls even() , and thread C calls odd() . Modify ZeroEvenOdd such that given n=6 , it outputs…

Print FooBar Alternately

Problem Statement You&rsquo;re given the FooBar class: class FooBar : def __init__ ( self , n ): self . n = n def foo ( self , printFoo : 'Callable[[], None]' ) -> None : for _ in range ( self . n ): printFoo () def bar ( self , printBar : 'Callable[[], None]' ) -> None : for _ in range ( self . n ): printBar () &hellip; and the same instance of FooBar will be passed to two different threads.…

Earliest Finish Time for Land and Water Rides

Problem Statement There are \(L\) possible land rides and \(W\) possible water rides, with \(1 \le L, W \le 5 \times 10^4\). A tourist must experience exactly one ride from each category, in either order. A ride may be started at its opening time or any later moment. Immediately after finishing one ride, the tourist may board the other if it&rsquo;s already open or wait until it opens. Return the…

Thread-Based Parallelism in Python

In Chromium, why wasn&rsquo;t explicit threading a thing? Data structures are usually not thread-safe. There were guardrails for scenarios like checking WeakPtr s on a different thread. However, I didn&rsquo;t come out of it with a mental model for threading primitives. Introduction Threads are smaller units of a process that allow executing tasks in parallel, sharing memory space. Threads are…

Minimum Cost of Buying Candies with Discount

The customer can choose any candy to takeaway for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Find the minimum cost of buying all the candies. Implementation: Sort then Traverse def minimumCost ( self , cost : List [ int ]) -> int : cost . sort ( reverse = True ) minCost = 0 for i in range ( len ( cost )): if i % 3 != 2 :…

Print in Order

Suppose we have a class: public class Foo { public void first () { print ( 'first' ); } public void second () { print ( 'second' ); } public void third () { print ( 'third' ); } } &hellip; and the same instance of Foo is passed to three different threads. Thread A will call first() , thread B will call second() and thread C will call third() . Design Foo such that second() is executed after…

Daredevil: Cold Day in Hell

MATT. &ldquo;All part of God&rsquo;s plan.&rdquo; What a beautiful phrase. Kind of covers it all. Dark. Light. Don&rsquo;t get yourself bothered. It&rsquo;s all God&rsquo;s plan . Nothing you could have done about it in any case. I understand the attraction. It&rsquo;s a nice bit of hand-waving. A catchall that pushes aside the necessity for deeper examination of responsibility. MATT. Rage.…

Delivery Framework for System Design Interviews

Requirements (~5min) Functional Requirements Completions for &ldquo;Users/Clients should be able to&hellip;&rdquo;, e.g., for Twitter: post tweets, follow other users, and see tweets from users they follow. Keep the list targeted and prioritized (e.g., top 3) as your job is to develop a system that meets those requirements. Non-Functional Requirements Completions for &ldquo;The system should…

Valid Sudoku

Determine if a \(9 \times 9\) Sudoku board is valid. A Sudoku board has nine \(3 \times 3\) sub-boxes. Validate the filled cells such that each row, column, and sub-box contain the digits \([1, &hellip;, 9]\) without repetition. Unintuitive to me that given a char c , we need c - '0' to convert it into an int . Convert.ToInt32('4') gives us 52 , not 4 . I don&rsquo;t think we can do better than…

Is Subsequence

Given two lowercase strings, s and t , return true if s is a subsequence of t , or false otherwise. A subsequence of a string is a string that is formed from the original string by deleting some (can be none) of the characters while maintaining the relative positions of the remaining characters. My solution was: public class Solution { private string _s ; private string _t ; public bool…

Minimum Size Subarray Sum

Given an array of positive integers nums and a positive integer target , return the minimal length of a subarray whose sum is greater than or equal to target . Return 0 if there is no such subarray. This reads like an \(^{n}P_{k}\) permutation problem, where we&rsquo;re trying to minimize \(k\) under the constraint that the sum of elements is greater than target . \(^{n}P_{k}\) can be implemented…

Remove Duplicates from Sorted Array

Given a sorted integer array, remove some duplicates in-place such that each unique element appears at most twice. Maintain the relative order of the elements. If there are \(k\) elements after removing the duplicates, the first \(k\) elements of the array should hold the final result. This a two-pointer problem, where we have a tortoise and a hare. Establishing an invariant that must be…

Rotate Array

Given an integer array of length \(N\), rotate the array to the right by \(k\) steps, where \(k \ge 0\). Rotation is periodical, e.g., rotating a 5-item array 13 times yields the same result as rotating it \( 13 \mod 5 = 3\) times. So our effective \(k\) is \(k \mod N\). That \(k \ge 0\) saves us from worrying about how the programming language implements modulo operations .

Two Sum

Problem Description Given a 1-indexed array of integers that is sorted in non-decreasing order, find two numbers such that they add up to a target number. Solution: Linear Scan with Binary Search #binary-search At its core, the problem is a binary search one. Given \(a\), find \(b = t - a\) in the right side of array . If \(a > \lfloor t / 2 \rfloor\), then there is no possible \(b\) to the right…

Majority Element in Array

Given an array of size \(N\), return the element that appears more than \(\lfloor N/2 \rfloor\) times. Solve the problem in \(\mathcal{O}(N)\) time and \(\mathcal{O}(1)\) space. Solving this in \(\mathcal{O}(N)\) time precludes sorting as that takes \(\mathcal{O}(N\ logN)\) time. Using \(\mathcal{O}(1)\) space precludes having a dictionary of frequencies. What is special about a frequency that is…

Merging Sorted Arrays

Merge Sorted Arrays In-Place With Buffer You are given two integer arrays nums1 and nums2 , sorted in non-decreasing order, and two integers m and n representing the number of elements in nums1 and nums2 respectively. nums1 has a length of \(m + n\). Merge nums1 and nums2 into nums1 in non-decreasing order. We don&rsquo;t want to use extra \(\mathcal{O}(m + n)\) space. Traversing nums1 and nums2…

The New Gods (2024)

Conflict MAXWELL LORD. What he failed to understand, my friend, is that it is human nature. To find things that are better than us &ndash; godly, wondrous divine things &ndash; and drag them down and pull them apart. Until there isn&rsquo;t very much godly or divine about them at all. THE CHRONICLER. Having foreseen his imminent capture and inevitable end, Parzurem had already fractured his mind…

Everything Dead & Dying (2025)

Everything Dead & Dying . Tate Brombal; Jacob Phillips. imagecomics.com . www.hoopladigital.com . 2025. Characterization JACK. Once upon a time, in a quiet, little town, there lived a farmer , and he was a good farmer. It was all he knew, after all. And the farmer worked his land from sunrise to sunset every single day. Tillin&rsquo; his fields, feedin&rsquo; his chickens, and collectin&rsquo; his…

Dictionary-Based Implementation of Classes and Objects (Python)

implements a toy version of Python&rsquo;s object system using dictionaries that contain references to properties, functions and other dictionaries. Consider two shapes, Square and Circle , with the methods perimeter , area , and density . Objects A function is an object, where the bytes in a function are instructions. For example: def foo (): print ( 'in foo' ) &hellip; creates an object in…

Model Context Protocol (MCP)

MCP is written with LLM apps as the clients, not human end-users. It provides a set of conventions on how to agnostically provide context to LLM apps. MCP 101 There are 3 key participants in the MCP architecture: MCP Host : The AI application that manages one or more MCP clients, e.g., Claude Code, Copilot, etc. MCP Client : A component that maintains a connection to an MCP server and obtains…

Societal Effects of LLMs

Chatbot Ethics Zuckerberg: But if you think something someone is doing is bad and they think it&rsquo;s really valuable, most of the time in my experience, they&rsquo;re right and you&rsquo;re wrong. You just haven&rsquo;t come up with the framework yet for understanding why the thing they&rsquo;re doing is valuable and helpful in their life. A user&rsquo;s expectations on what is permissible for…

Absolute Wonder Woman (2024 -)

Justice DIANA. And for you , Harbinger Prime, Nemesis will be a particular hell. For she binds and burns in proportion to your sins&hellip; and your soul shines bright with the blood of the innocent. The burn you feel, Harbinger&hellip; Know that it is the result of the pain you have wrought on others. All you are feeling, you have earned. Accept Nemesis&rsquo;s judgement of you.

Absolute Superman

Technocracy KAL-EL. In the cities worked the klerics of the science league. Harnessing the energies of the red sun and the planet itself to fuel their insatiable hunger&hellip; for progress&hellip; at all costs. TEACHER. You&hellip; wrote this? Yourself? That&rsquo;s&hellip; Kal, the luminarium contains all knowledge of the science league from throughout Kryptonian history and can answer any…

AoC 2024 Day 16: Reindeer Maze

Data Parsing The input is an \(R \times C\) grid with # for a wall, S for the start tile, E for the end tile, and . for open spots. Part One The reindeer start at S facing East , and can move one tile at a time, increasing their score by 1 point. They can also rotate clockwise or counterclockwise 90 degrees at a time, increasing their score by 1000 points. What is the lowest score a Reindeer could…

Tons of Buttons

This page shows 100,000 buttons. Use https://www.curiosities.dev/computer-science/large-language-models/toy-pages/tons-of-buttons/?numButtons=1000 to show 1,000 buttons instead. Click on a button to activate it. Click again to deactivate it. Activated buttons are highlighted in green. There are currently 0 activated buttons: {empty} .

AoC 2024 Day 15: Warehouse Woes

Parsing ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv<v>>v<< v^^>>><<v^^>>>^ @ denotes the robot, O denotes a box, and # denotes a wall. <^^>>>vv<v>>v<< describes the sequence of moves that the robot will attempt to make. Ignore the newlines within the move sequence. If there are any boxes in the way, the robot attempts to push them. However, if the action makes…

Software Design By Example: A Tool-Based Introduction with JavaScript

Software Design by Example . A Tool-Based Introduction with JavaScript . Greg Wilson. third-bit.com . Accessed Jan 20, 2026. Also contains exercises at the end of each chapter. Systems Programming . List a directory. Callback functions. Anonymous functions. Select a set of files. Copying a set of files. Asynchronous Programming . Manage async executions. How promises work. Chain operations. How…

Software Design By Example: A Tool-Based Introduction with Python

Software Design by Example . A Tool-Based Introduction with Python . Greg Wilson. third-bit.com . Accessed Jan 20, 2026. ✅ Objects and Classes . What is a natural way to represent real-world &ldquo;things&rdquo; in code, and how can we organize that code so that it&rsquo;s easier to understand, test, and extend? Finding Duplicate Files . Comparing each file to others is unworkably slow for large…

500 Lines or Less

The Architecture of Open Source Applications . 500 Lines or Less . aosabook.org . Accessed Jan 19, 2026. Blockcode: A Visual Programming Toolkit . A well-done block language eliminates syntax errors, visually displays available components, and allows localization. A Continuous Integration System . A dedicated system used to test new code. Clustering by Consensus . A network protocol designed to…

Architecture of Open Source Applications, Vol. 1

The Architecture of Open Source Applications . Volume 1 . aosabook.org . Accessed Jan 19, 2026. Asterisk . A server application for making, receiving, and performing custom processing of phone calls. Audacity . A popular sound recorder and audio editor. One goal is that its user interface should be discoverable: people should be able to sit down without a manual and start using it right away.

Architecture of Open Source Applications, Vol. 2

The Architecture of Open Source Applications . Volume 2 . aosabook.org . Accessed Jan 19, 2026. Scalable Web Architecture and Distributed Systems . Key issues to consider when designing large websites, and some of the building blocks used to achieve these goals. Firefox Release Engineering . Scripts and infrastructure decisions that comprise the complete Firefox rapid release system. Starting with…

The Performance of Open Source Applications

The Architecture of Open Source Applications . The Performance of Open Source Applications . Tavish Armstrong. aosabook.org . Sep 26, 2013. Accessed Jan 19, 2026. ✅ High Performance Networking in Chrome . Many of the sites we use today are not just web pages, they are applications. How do we make the fastest browser? Notes . From SocialCalc to EtherCalc . EtherCalc is an online spreadsheet system…

Babel, or the Necessity of Violence

Babel, or the Necessity of Violence . An Arcane History of the Oxford Translators' Revolution . R. F. Kuang. en.wikipedia.org . Aug 23, 2022. ISBN: 9780063021426 . Accessed Jan 17, 2026. On Language Language was always the companion of the empire, and as such, together they begin, grow, and flourish. And later, together, they fall.

AoC 2024 Day 14: Restroom Redoubt

Parsing The input is a list of all robots&rsquo; current positions \(p = (x, y)\) and velocities \(v = (dx, dy)\), one robot per line, e.g., p=3,6 v=4,-7 p=9,2 v=-1,-2 \(x\) represents the number of tiles away from the left wall, and similarly for \(y\) from the top wall (when viewed from above). The top-left corner of the space is \((0, 0)\). The velocity is given in tiles per second.

C# Performance Tools

BenchmarkDotNet Some work projects use BenchmarkDotNet as the .NET library for benchmarking. Getting familiar with it should pay dividends. To run the benchmarks in the Day13ClawContraption class: dotnet run -c Release -- -f '*Day13ClawContraption*' A job describes how to run your benchmark, e.g, ID, environment, run settings. BenchmarkDotNet has a smart algorithm for choosing values like…