<?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 Krish Srivastava on Medium]]></title>
        <description><![CDATA[Stories by Krish Srivastava on Medium]]></description>
        <link>https://medium.com/@krizzsrivastava?source=rss-30c8ba8983ce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BvNq6V5YVtQD8t8mODmYmQ.jpeg</url>
            <title>Stories by Krish Srivastava on Medium</title>
            <link>https://medium.com/@krizzsrivastava?source=rss-30c8ba8983ce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:23:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krizzsrivastava/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[Building a Distributed Key-Value Store in a Weekend: dht]]></title>
            <link>https://medium.com/@krizzsrivastava/building-a-distributed-key-value-store-in-a-weekend-dht-958bf00525da?source=rss-30c8ba8983ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/958bf00525da</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[key-value-store]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Krish Srivastava]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 05:23:20 GMT</pubDate>
            <atom:updated>2025-11-17T05:23:20.496Z</atom:updated>
            <content:encoded><![CDATA[<h3>The “Why the Hell Not?” Moment</h3><p>You know that feeling when you’re setting up Redis for the 100th time, configuring sentinels, managing cluster slots, and you think: “There has to be a simpler way”?</p><p>That was my Friday evening. By Sunday night, I had <strong>dht</strong> — a distributed key-value store that actually makes sense.</p><p><strong>GitHub</strong>: <a href="https://github.com/retr0-kernel/dht">retr0-kernel/dht</a> ⭐ (<strong>Open for contributions!</strong>)</p><h3>What I Built</h3><p>A globally distributed KV store with:</p><ul><li><strong>Dual consistency modes</strong> (choose speed OR correctness per request)</li><li><strong>Zero cluster bullshit</strong> (consistent hashing handles it)</li><li><strong>Beautiful dashboard</strong> (because CLIs are overrated)</li><li><strong>Production-ready features</strong> (WAL, replication, rate limiting)</li></ul><p>Think Redis meets DynamoDB, but you can actually understand how it works.</p><h3>The Core Concepts (Without the PhD)</h3><h3>Distributed Hash Tables: The 30-Second Version</h3><p>Traditional databases have a master that coordinates everything. DHTs are peer-to-peer — no boss, just nodes helping each other.</p><blockquote><strong>Traditional: <br></strong>Client → Master → Replicas (master = bottleneck)</blockquote><blockquote><strong>DHT: <br></strong>Client → Any Node → Right Node (no bottleneck)</blockquote><h3>Consistent Hashing: The Magic Sauce</h3><p><strong>Problem</strong>: How do you distribute keys across servers without reshuffling everything when you add/remove nodes?</p><p><strong>Naive approach</strong> (what <strong>NOT</strong> to do):</p><pre>server = hash(key) % num_servers<br><br># With 3 servers:<br>hash(&quot;user:123&quot;) % 3 = Server 0<br>hash(&quot;session:abc&quot;) % 3 = Server 2<br><br># Add 4th server:<br>hash(&quot;user:123&quot;) % 4 = Server 3  # MOVED!<br>hash(&quot;session:abc&quot;) % 4 = Server 2  # Stayed<br><br># Result: 75% of keys need to move. Disaster!</pre><h4><strong>Consistent Hashing Solution</strong>:</h4><p>Instead of mod, we use a <strong>hash ring</strong>. Both keys AND servers get hashed onto the same ring (0 to 2³²-1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRL1ZUAdNBU4K5tiZB7x6Q.png" /></figure><h4><strong>How it works</strong>:</h4><ol><li><strong>Hash the key</strong>: FNV1a(&quot;user:123&quot;) → 45</li><li><strong>Walk clockwise</strong> on ring until you hit a virtual node</li><li><strong>Map to physical node</strong>: Virtual node 45 → Node A</li></ol><h4><strong>Virtual nodes</strong> (the secret weapon):</h4><p>Instead of putting each physical node once on the ring, we put it 150 times (virtual nodes). Why?</p><pre>Without virtual nodes:<br>- Node A gets hash range 0-1000<br>- Node B gets hash range 1001-5000  (4x more keys!)<br>- Unbalanced → Node B overloaded<br><br>With 150 virtual nodes:<br>- Node A has 150 positions spread evenly<br>- Node B has 150 positions spread evenly  <br>- Balanced → Each gets ~33% of keys</pre><h4>When you add/remove nodes</h4><pre><strong>Initial:</strong> 3 nodes, 1000 keys<br>Add Node D:<br>  - Only keys between C and D move (~250 keys = 25%)<br>  - Other 750 keys stay put<br><br><strong>Traditional mod approach:<br></strong>  - 750 keys move (75%)<br>  <br><em>10x less data movement!</em></pre><h4>Why FNV-1a hash?</h4><ul><li>Fast: O(n) where n = key length</li><li>Uniform distribution: Keys spread evenly</li><li>Low collision rate: Different keys rarely get same hash</li><li>Avalanche effect: Change 1 bit → 50% of hash bits change</li></ul><h4>The CAP Theorem Reality Check:</h4><p>You’ve probably seen this triangle in every distributed systems class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Am5UOa2SULIAfeqc" /></figure><p>Pick 2, they said. But here’s the thing: <strong>Partition tolerance isn’t optional</strong> (networks fail). So you’re really choosing between:</p><p><strong>CP (Consistency + Partition tolerance):</strong></p><ul><li>During a network split: Refuse writes to stay consistent</li><li>Example: Banking — Better to be unavailable than show wrong balance</li><li>Tradeoff: System might return errors during partitions</li></ul><p><strong>AP (Availability + Partition tolerance):</strong></p><ul><li>During a network split: Accept writes, fix conflicts later</li><li>Example: Social media — Better to show slightly stale feed than no feed</li><li>Tradeoff: Different users might see different data temporarily</li></ul><h4>The PACELC Extension (the part they don’t teach):</h4><p>CAP only talks about partitions. But what about normal operation?</p><pre>If Partition:<br>    Choose Availability OR Consistency<br>Else (normal operation):<br>    Choose Latency OR Consistency</pre><p>This is where it gets interesting:</p><h4>Eventual Consistency (PA/EL)</h4><p><strong>Partition:</strong> Available (accept writes) <br><strong>Normal:</strong> Low Latency (async replication)</p><p><strong>Benefits:<br></strong>- Fast writes (~100ms)<br>- Always available<br>- Scales horizontally</p><p><strong>Tradeoffs:<br></strong>- Stale reads possible<br>- Conflicts need resolution</p><h4><strong>Strong Consistency (PC/EC)</strong></h4><p><strong>Partition:</strong> Consistent (reject writes if can’t replicate) <br><strong>Normal:</strong> Higher Latency (wait for replicas)</p><p>Benefits:<br>- Always correct data <br>- No conflicts<br>- Simple reasoning</p><p><strong>Tradeoffs:<br>- </strong>Slower writes (~400ms)<br>- Might be unavailable during failures</p><p><strong>dht’s approach</strong>: Why choose? Let the user decide per request!</p><pre>// Fast mode for cache<br>await fetch(&#39;/v1/kv/cache:weather&#39;, {<br>  headers: { &#39;X-Consistency&#39;: &#39;eventual&#39; }  // PA/EL<br>});<br><br>// Reliable mode for money<br>await fetch(&#39;/v1/kv/balance:user123&#39;, {<br>  headers: { &#39;X-Consistency&#39;: &#39;strong&#39; }    // PC/EC<br>});</pre><h3>Real-world CAP in action</h3><p>Imagine a network partition splits your 3 nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkW_SH8mzztwweWMFFHZxw.png" /></figure><h4>Eventual Consistency behavior</h4><p>Client 1 → Write to Node A → Success (available)<br>Client 2 → Read from Node B → Stale data (inconsistent)</p><p>After partition heals:<br>- Node A’s writes replicate to B, C<br>- Conflicts resolved by timestamp (Last-Write-Wins)<br>- Eventually consistent</p><h4>Strong Consistency behavior</h4><p>Client 1 → Write to Node A → Try replicate to B, C<br> → Can’t reach B, C (partition)<br> → Need 2/3 for quorum<br> → Only have 1/3<br> → REJECT WRITE (unavailable but consistent)</p><p>Client 2 → Read from Node B → Success (sees latest committed data)</p><p><strong>The beautiful part</strong>: Same infrastructure, different guarantees. You choose based on your use case.</p><h3>Architecture: How It Actually Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kt3QghRki2cyu2ZyzgovFA.png" /><figcaption>HLD</figcaption></figure><h3>1. API Gateway (The Bouncer)</h3><p><strong>Role</strong>: Single entry point for all requests. Validates, routes, and enforces limits.</p><p><strong>Internal Architecture</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQAOmAbZn1-k60qwyu-ZBA.png" /></figure><p><strong>Request Flow</strong>:</p><pre>// 1. Receive request<br>POST /v1/kv/user:123<br>Headers: X-API-Key: ydht_abc123<br><br>// 2. Validate API key<br>apiKey := r.Header.Get(&quot;X-API-Key&quot;)<br>user, err := userManager.ValidateKey(apiKey)<br>if err != nil {<br>    return 401 Unauthorized<br>}<br><br>// 3. Rate limiting (per user)<br>if !rateLimiter.Allow(user.ID) {<br>    return 429 Too Many Requests<br>}<br><br>// 4. Consistent hashing to find node<br>targetNode := hashRing.GetNode(&quot;user:123&quot;)<br>// Returns: &quot;http://localhost:8082&quot;<br><br>// 5. Proxy to DHT node<br>response := http.Post(targetNode + &quot;/store/user:123&quot;, body)<br><br>// 6. Track metrics<br>metrics.RecordRequest(user.ID, latency, statusCode)<br><br>// 7. Return to client<br>return response</pre><p><strong>Key Components</strong>:</p><ul><li><strong>Hash Ring</strong>: 3 physical nodes × 150 virtual nodes = 450 positions</li><li><strong>Rate Limiter</strong>: Token bucket (100 req/min per user, burst of 10)</li><li><strong>Metrics</strong>: Records every request for analytics dashboard</li></ul><h3>2. User Manager (The Identity System)</h3><p><strong>Role</strong>: Authentication, API key management, usage analytics.</p><p><strong>Internal Architecture</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0Y4LHya1WClPFsMe-SZoQ.png" /></figure><p><strong>Database Schema</strong>:</p><pre>-- Users table<br>CREATE TABLE users (<br>    id SERIAL PRIMARY KEY,<br>    email VARCHAR(255) UNIQUE NOT NULL,<br>    username VARCHAR(100) UNIQUE NOT NULL,<br>    password_hash VARCHAR(255) NOT NULL,<br>    created_at TIMESTAMP DEFAULT NOW()<br>);<br><br>-- API Keys table<br>CREATE TABLE api_keys (<br>    id SERIAL PRIMARY KEY,<br>    user_id INTEGER REFERENCES users(id),<br>    key_hash VARCHAR(255) UNIQUE NOT NULL,  -- We store hash, not plain key<br>    name VARCHAR(100),<br>    scopes TEXT[],  -- [&#39;read&#39;, &#39;write&#39;]<br>    expires_at TIMESTAMP,<br>    last_used_at TIMESTAMP,<br>    created_at TIMESTAMP DEFAULT NOW()<br>);<br><br>-- Usage stats table<br>CREATE TABLE usage_stats (<br>    id SERIAL PRIMARY KEY,<br>    user_id INTEGER REFERENCES users(id),<br>    api_key_id INTEGER REFERENCES api_keys(id),<br>    operation VARCHAR(20),  -- GET, PUT, DELETE<br>    key_name TEXT,<br>    status_code INTEGER,<br>    latency_ms INTEGER,<br>    created_at TIMESTAMP DEFAULT NOW()<br>);</pre><p><strong>API Key Generation</strong>:</p><pre>func (s *Service) CreateAPIKey(userID int, name string) (string, error) {<br>    // 1. Generate cryptographically random key<br>    randomBytes := make([]byte, 32)<br>    rand.Read(randomBytes)<br>    plainKey := &quot;ydht_&quot; + base64.URLEncoding.EncodeToString(randomBytes)<br>    <br>    // 2. Hash for storage (we NEVER store plain keys)<br>    keyHash := sha256.Sum256([]byte(plainKey))<br>    <br>    // 3. Store hash in database<br>    _, err := s.db.Exec(`<br>        INSERT INTO api_keys (user_id, key_hash, name)<br>        VALUES ($1, $2, $3)<br>    `, userID, hex.EncodeToString(keyHash[:]), name)<br>    <br>    // 4. Return plain key to user (ONLY TIME they see it)<br>    return plainKey, err<br>}<br><br>func (s *Service) ValidateKey(plainKey string) (*User, error) {<br>    // Hash the provided key<br>    keyHash := sha256.Sum256([]byte(plainKey))<br>    <br>    // Look up in database<br>    var userID int<br>    err := s.db.QueryRow(`<br>        SELECT user_id FROM api_keys<br>        WHERE key_hash = $1 AND (expires_at IS NULL OR expires_at &gt; NOW())<br>    `, hex.EncodeToString(keyHash[:])).Scan(&amp;userID)<br>    <br>    if err != nil {<br>        return nil, errors.New(&quot;invalid or expired key&quot;)<br>    }<br>    <br>    // Update last_used_at<br>    s.db.Exec(&quot;UPDATE api_keys SET last_used_at = NOW() WHERE key_hash = $1&quot;, <br>              hex.EncodeToString(keyHash[:]))<br>    <br>    return s.GetUser(userID)<br>}</pre><p><strong>Why hash API keys?</strong></p><ul><li>Database breach doesn’t leak working keys</li><li>Same reason we hash passwords</li><li>Irreversible: Can’t derive plainKey from keyHash</li></ul><h3>3. DHT Nodes (The Storage Layer)</h3><p><strong>Role</strong>: Store key-value pairs, handle replication, recover from crashes.</p><p><strong>Internal Architecture</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3333pmKl560KCWs-MVDRg.png" /></figure><p><strong>Storage Entry Structure</strong>:</p><pre>type Entry struct {<br>    Key       string      `json:&quot;key&quot;`<br>    Value     interface{} `json:&quot;value&quot;`<br>    CreatedAt time.Time   `json:&quot;created_at&quot;`<br>    UpdatedAt time.Time   `json:&quot;updated_at&quot;`<br>    ExpiresAt *time.Time  `json:&quot;expires_at,omitempty&quot;`  // nil = no expiry<br>}<br><br>type Storage struct {<br>    data map[string]Entry  // In-memory hash map<br>    mu   sync.RWMutex      // Thread-safe reads/writes<br>}</pre><p><strong>Write Path (PUT operation)</strong>:</p><pre>func (n *DHTNode) HandlePut(key string, value interface{}, ttl string) error {<br>    // 1. Parse TTL if provided<br>    var expiresAt *time.Time<br>    if ttl != &quot;&quot; {<br>        duration := parseTTL(ttl)  // &quot;1h&quot; -&gt; 1 hour<br>        expiry := time.Now().Add(duration)<br>        expiresAt = &amp;expiry<br>    }<br>    <br>    // 2. Create entry<br>    entry := Entry{<br>        Key:       key,<br>        Value:     value,<br>        CreatedAt: time.Now(),<br>        UpdatedAt: time.Now(),<br>        ExpiresAt: expiresAt,<br>    }<br>    <br>    // 3. Write to WAL FIRST (durability)<br>    err := n.wal.Append(entry)<br>    if err != nil {<br>        return err<br>    }<br>    <br>    // 4. Then update memory<br>    n.storage.mu.Lock()<br>    n.storage.data[key] = entry<br>    n.storage.mu.Unlock()<br>    <br>    return nil<br>}</pre><p><strong>Write-Ahead Log (WAL)</strong>:</p><pre>type WAL struct {<br>    file *os.File<br>    mu   sync.Mutex<br>}<br><br>func (w *WAL) Append(entry Entry) error {<br>    w.mu.Lock()<br>    defer w.mu.Unlock()<br>    <br>    // 1. Serialize to JSON<br>    data, _ := json.Marshal(entry)<br>    <br>    // 2. Write to file<br>    _, err := w.file.Write(append(data, &#39;\n&#39;))<br>    if err != nil {<br>        return err<br>    }<br>    <br>    // 3. CRITICAL: fsync to disk<br>    // This ensures data survives power loss<br>    return w.file.Sync()<br>}<br><br>func (n *DHTNode) RecoverFromWAL() error {<br>    file, _ := os.Open(&quot;wal.log&quot;)<br>    scanner := bufio.NewScanner(file)<br>    <br>    // Replay all operations<br>    for scanner.Scan() {<br>        var entry Entry<br>        json.Unmarshal(scanner.Bytes(), &amp;entry)<br>        <br>        // Restore to memory<br>        n.storage.data[entry.Key] = entry<br>    }<br>    <br>    return scanner.Err()<br>}</pre><p><strong>TTL Management</strong>:</p><pre>func (n *DHTNode) StartTTLCleaner() {<br>    ticker := time.NewTicker(1 * time.Minute)<br>    <br>    go func() {<br>        for range ticker.C {<br>            n.cleanExpiredKeys()<br>        }<br>    }()<br>}<br><br>func (n *DHTNode) cleanExpiredKeys() {<br>    now := time.Now()<br>    n.storage.mu.Lock()<br>    defer n.storage.mu.Unlock()<br>    <br>    for key, entry := range n.storage.data {<br>        if entry.ExpiresAt != nil &amp;&amp; now.After(*entry.ExpiresAt) {<br>            delete(n.storage.data, key)<br>            // Also write DELETE to WAL<br>            n.wal.Append(Entry{Key: key, Operation: &quot;DELETE&quot;})<br>        }<br>    }<br>}</pre><h3>4. Replicator (The Consistency Guardian)</h3><p><strong>Role</strong>: Copies data across nodes based on consistency mode.</p><p><strong>Internal Architecture</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*oV613vhqpVlQlP2MiXp5gA.png" /></figure><p><strong>Eventual Consistency Replication</strong>:</p><pre>func (r *Replicator) ReplicateEventual(key, value string, primaryNode string) {<br>    // Async - returns immediately<br>    go func() {<br>        replicas := r.getReplicas(key, primaryNode)  // Get 2 other nodes<br>        <br>        for _, replicaURL := range replicas {<br>            // Best effort - retry on failure<br>            for attempt := 0; attempt &lt; 3; attempt++ {<br>                err := r.sendToReplica(replicaURL, key, value)<br>                if err == nil {<br>                    break  // Success<br>                }<br>                time.Sleep(time.Duration(attempt) * time.Second)  // Exponential backoff<br>            }<br>        }<br>        <br>        r.metrics.RecordReplication(&quot;eventual&quot;, time.Since(start))<br>    }()<br>}</pre><p><strong>Strong Consistency Replication</strong>:</p><pre>func (r *Replicator) ReplicateStrong(key, value string, primaryNode string) error {<br>    replicas := r.getReplicas(key, primaryNode)<br>    <br>    // Parallel replication<br>    results := make(chan error, len(replicas))<br>    for _, replicaURL := range replicas {<br>        go func(url string) {<br>            results &lt;- r.sendToReplica(url, key, value)<br>        }(replicaURL)<br>    }<br>    <br>    // Wait for majority ACK (2 out of 3 nodes)<br>    successCount := 1  // Primary already has it<br>    for i := 0; i &lt; len(replicas); i++ {<br>        err := &lt;-results<br>        if err == nil {<br>            successCount++<br>        }<br>        <br>        // Check if we have majority<br>        if successCount &gt;= 2 {  // 2/3 = majority<br>            return nil  // Success!<br>        }<br>    }<br>    <br>    // Failed to get majority<br>    return errors.New(&quot;failed to achieve quorum&quot;)<br>}</pre><p><strong>Replica Selection</strong>:</p><pre>func (r *Replicator) getReplicas(key, primaryNode string) []string {<br>    // Get next 2 nodes clockwise on hash ring<br>    allNodes := r.ring.GetAllNodes()  // [NodeA, NodeB, NodeC]<br>    <br>    // Find primary&#39;s position<br>    primaryIdx := indexOf(allNodes, primaryNode)<br>    <br>    // Get next 2 nodes (wrap around if needed)<br>    replicas := []string{<br>        allNodes[(primaryIdx+1) % len(allNodes)],<br>        allNodes[(primaryIdx+2) % len(allNodes)],<br>    }<br>    <br>    return replicas<br>}</pre><p><strong>Metrics Tracking</strong>:</p><pre>type ReplicationMetrics struct {<br>    TotalReplications  int64<br>    SuccessCount       int64<br>    FailureCount       int64<br>    AverageLatency     time.Duration<br>    EventualLag        time.Duration  // How long until all replicas have data<br>}<br><br>func (r *Replicator) RecordReplication(mode string, latency time.Duration) {<br>    r.metrics.mu.Lock()<br>    defer r.metrics.mu.Unlock()<br>    <br>    r.metrics.TotalReplications++<br>    r.metrics.AverageLatency = <br>        (r.metrics.AverageLatency + latency) / 2  // Running average<br>    <br>    if mode == &quot;eventual&quot; {<br>        r.metrics.EventualLag = latency<br>    }<br>}</pre><h3>Consistency Modes Explained (The Heart of the System)</h3><p>This is the core feature that makes <strong>dht</strong> different. Let me break it down properly.</p><h3>The Problem We’re Solving</h3><p>Traditional systems force you to pick ONE consistency model:</p><ul><li>Redis: Eventual (fast but might be stale)</li><li>PostgreSQL: Strong (reliable but slower)</li></ul><p><strong>dht</strong>: Why not both? Let the user choose per request!</p><h3><strong>Eventual Consistency</strong> (Fast &amp; Furious):</h3><p><strong>Promise</strong>: “All replicas will eventually have the same data, but reads might be stale for ~100–500ms”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGj6Fpj8AGUTMNUbxdWuhg.png" /></figure><p><strong>The Stale Read Scenario</strong>:</p><pre>// User A writes<br>await fetch(&#39;/v1/kv/cart:123&#39;, {<br>  method: &#39;PUT&#39;,<br>  headers: { <br>    &#39;X-API-Key&#39;: key,<br>    &#39;X-Consistency&#39;: &#39;eventual&#39;  <br>  },<br>  body: JSON.stringify({ items: [&#39;laptop&#39;] })<br>});<br>// Returns in 100ms<br><br>// User A reads (immediately after)<br>// Hits primary node -&gt; Sees latest data <br><br>// User B reads (different region, hits replica)<br>// t=150ms: Replica hasn&#39;t received data yet<br>// Returns old/empty cart<br><br>// User B reads again at t=400ms<br>// Replica now has the data<br>// Returns correct cart</pre><p><strong>When to use Eventual</strong>:</p><p><strong>1. Session Storage</strong> (perfect fit):</p><pre>// Each user only accesses their own session<br>// Stale reads across users don&#39;t matter<br>await storeSession(userId, sessionData, { consistency: &#39;eventual&#39; });</pre><p><strong>2. Caching</strong> (perfect fit):</p><pre># Cache is inherently stale by nature<br># 100ms staleness &lt; 5min TTL<br>cache_key = f&quot;weather:{city}&quot;<br>store_data(cache_key, weather_data, ttl=&#39;5m&#39;, consistency=&#39;eventual&#39;)</pre><p><strong>3. Analytics Events</strong> (perfect fit):</p><pre>// Slightly delayed metrics are fine<br>// Throughput &gt; accuracy<br>event := Event{UserID: 123, Action: &quot;click&quot;, Timestamp: time.Now()}<br>storeData(&quot;event:&quot;+uuid, event, &quot;eventual&quot;)</pre><p>4. <strong>Social Media Feeds</strong> (perfect fit):</p><pre>// If like count shows 99 instead of 100 for 200ms, who cares?<br>await updateLikeCount(postId, newCount, { consistency: &#39;eventual&#39; });</pre><h4><strong>Conflict Resolution</strong> (Last-Write-Wins):</h4><pre>// What if two writes happen to different replicas during partition?<br><br>// Write 1 at t=100ms: cart = [&quot;laptop&quot;]<br>// Write 2 at t=150ms: cart = [&quot;phone&quot;]<br><br>// On convergence, we compare timestamps:<br>func resolve(entry1, entry2 Entry) Entry {<br>    if entry1.UpdatedAt.After(entry2.UpdatedAt) {<br>        return entry1  // Later write wins<br>    }<br>    return entry2<br>}<br><br>// Result: cart = [&quot;phone&quot;] (latest timestamp wins)</pre><h3><strong>Strong Consistency</strong> (Slow &amp; Steady):</h3><p><strong>Promise</strong>: “Every read sees the most recent write. Period. No stale data ever.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*flk09rEa2l_zkLi38LD5Gw.png" /></figure><h4>Quorum Math</h4><p>Total nodes (N) = 3<br>Write quorum (W) = 2 (need this many ACKs)<br>Read quorum (R) = 1 (read from primary)</p><p><strong>Rule: W + R &gt; N</strong><br> 2 + 1 &gt; 3 ✓</p><p>Why this works:<br>- Write to 2 nodes means at least 2 have latest data<br>- Read from 1 node (primary) always has latest<br>- Overlapping quorums guarantee consistency</p><h4><strong>The Linearizability Guarantee</strong>:</h4><pre>// Timeline of operations from different clients<br><br>// t=0: Client A writes balance = $100 (strong consistency)<br>await put(&#39;balance:123&#39;, 100, { consistency: &#39;strong&#39; });<br>// Completes at t=400ms (waits for replication)<br><br>// t=500: Client B reads balance (any node)<br>const balance = await get(&#39;balance:123&#39;);<br>// GUARANTEED to see $100 (not stale)<br><br>// t=600: Client C writes balance = $50<br>await put(&#39;balance:123&#39;, 50, { consistency: &#39;strong&#39; });<br>// Completes at t=1000ms<br><br>// t=1100: Client D reads balance<br>const newBalance = await get(&#39;balance:123&#39;);<br>// GUARANTEED to see $50 (latest write)<br><br>// No client will ever see: $100 → $0 → $50<br>// All clients see: $100 → $50 (total order preserved)</pre><h4><strong>When to use Strong</strong>:</h4><p>1. <strong>Financial Data</strong> (mandatory):</p><pre>// Account balance MUST be exact<br>async function transfer(from, to, amount) {<br>  const balance = await get(`balance:${from}`, { consistency: &#39;strong&#39; });<br>  <br>  if (balance &lt; amount) {<br>    throw new Error(&#39;Insufficient funds&#39;);<br>  }<br>  <br>  await put(`balance:${from}`, balance - amount, { consistency: &#39;strong&#39; });<br>  await put(`balance:${to}`, await get(`balance:${to}`) + amount, { consistency: &#39;strong&#39; });<br>}</pre><p>2. <strong>Inventory</strong> (mandatory):</p><pre># Can&#39;t oversell products<br>def purchase(item_id, quantity):<br>    inventory = get_data(f&#39;inventory:{item_id}&#39;, consistency=&#39;strong&#39;)<br>    <br>    if inventory[&#39;stock&#39;] &lt; quantity:<br>        return {&#39;error&#39;: &#39;Out of stock&#39;}<br>    <br>    inventory[&#39;stock&#39;] -= quantity<br>    store_data(f&#39;inventory:{item_id}&#39;, inventory, consistency=&#39;strong&#39;)<br>    return {&#39;success&#39;: True}</pre><p>3. <strong>User Authentication</strong> (mandatory):</p><pre>// Password change must be immediate everywhere<br>func ChangePassword(userID string, newPasswordHash string) error {<br>    return StoreData(<br>        fmt.Sprintf(&quot;password:%s&quot;, userID),<br>        newPasswordHash,<br>        &quot;strong&quot;,  // Security can&#39;t be eventual!<br>    )<br>}</pre><p>4. <strong>Distributed Locks</strong> (mandatory):</p><pre>// Only one process can hold the lock<br>async function acquireLock(resourceId) {<br>  const lockKey = `lock:${resourceId}`;<br>  <br>  // Check if lock exists (MUST be consistent)<br>  const existing = await get(lockKey, { consistency: &#39;strong&#39; });<br>  if (existing) {<br>    return false;  // Already locked<br>  }<br>  <br>  // Acquire lock<br>  await put(lockKey, { holder: processId, acquired: Date.now() }, <br>    { consistency: &#39;strong&#39;, ttl: &#39;5m&#39; });<br>  <br>  return true;<br>}</pre><h4><strong>Failure Handling</strong>:</h4><pre>func (r *Replicator) ReplicateStrong(key, value string) error {<br>    results := make(chan error, 2)<br>    <br>    // Replicate to 2 nodes in parallel<br>    for _, node := range replicas {<br>        go func(n string) {<br>            results &lt;- sendToReplica(n, key, value)<br>        }(node)<br>    }<br>    <br>    // Wait for 2 ACKs (quorum)<br>    successCount := 1  // Primary already wrote<br>    timeoutChan := time.After(5 * time.Second)<br>    <br>    for i := 0; i &lt; 2; i++ {<br>        select {<br>        case err := &lt;-results:<br>            if err == nil {<br>                successCount++<br>                if successCount &gt;= 2 {<br>                    return nil  // Quorum reached!<br>                }<br>            }<br>        case &lt;-timeoutChan:<br>            return errors.New(&quot;replication timeout - failed to achieve quorum&quot;)<br>        }<br>    }<br>    <br>    return errors.New(&quot;insufficient ACKs for quorum&quot;)<br>}</pre><h3>Real-World Usage: Where This Actually Helps</h3><h3>1. Session Storage (Eventual = Perfect)</h3><pre>// E-commerce shopping cart<br>await fetch(&#39;http://api.dht.com/v1/kv/cart:user123?ttl=2h&#39;, {<br>  method: &#39;PUT&#39;,<br>  headers: {<br>    &#39;X-API-Key&#39;: process.env.DHT_KEY,<br>    &#39;X-Consistency&#39;: &#39;eventual&#39;  // Fast writes, who cares about 100ms staleness?<br>  },<br>  body: JSON.stringify({<br>    items: [{id: &#39;laptop&#39;, qty: 1, price: 999}],<br>    total: 999<br>  })<br>});Java</pre><p><strong>Why eventual works</strong>: Your cart doesn’t need to be globally consistent. You’re the only one seeing it.</p><h3>2. API Response Caching (Eventual = Perfect)</h3><pre>def cached_weather_api(city):<br>    cache_key = f&quot;weather:{city}&quot;<br>    <br>    # Try cache first<br>    cached = get_data(cache_key)<br>    if cached:<br>        return cached<br>    <br>    # Miss - fetch and cache<br>    weather = requests.get(f&quot;api.weather.com/{city}&quot;).json()<br>    store_data(cache_key, weather, ttl=&#39;5m&#39;, consistency=&#39;eventual&#39;)<br>    return weather</pre><p><strong>Why eventual works</strong>: Weather updates every 5 minutes. 100ms replication lag is nothing.</p><h3>3. User Accounts (Strong = Mandatory)</h3><pre>// Password change<br>await fetch(&#39;http://api.dht.com/v1/kv/password:user123&#39;, {<br>  method: &#39;PUT&#39;,<br>  headers: {<br>    &#39;X-API-Key&#39;: process.env.DHT_KEY,<br>    &#39;X-Consistency&#39;: &#39;strong&#39;  // MUST be consistent immediately<br>  },<br>  body: JSON.stringify({<br>    hash: bcrypt.hash(newPassword),<br>    updated_at: Date.now()<br>  })<br>});</pre><p><strong>Why strong required</strong>: Security can’t be eventually consistent. Password changes must be immediate everywhere.</p><h3>4. Inventory Management (Strong = Mandatory)</h3><pre>func purchaseItem(itemID string, quantity int) error {<br>    // Read with strong consistency<br>    inventory := getData(fmt.Sprintf(&quot;inventory:%s&quot;, itemID), &quot;strong&quot;)<br>    <br>    if inventory[&quot;quantity&quot;] &lt; quantity {<br>        return errors.New(&quot;out of stock&quot;)<br>    }<br>    <br>    // Write with strong consistency<br>    inventory[&quot;quantity&quot;] -= quantity<br>    storeData(fmt.Sprintf(&quot;inventory:%s&quot;, itemID), inventory, &quot;strong&quot;)<br>    <br>    return nil<br>}</pre><p><strong>Why strong required</strong>: You can’t oversell. Inventory must be exact across all nodes.</p><h3>The Technical Bits That Make It Work</h3><h4>Write-Ahead Logging (WAL)</h4><p>Every write hits disk before memory:</p><pre>// Simplified version<br>func (n *Node) Put(key, value string) error {<br>    // 1. Write to log FIRST<br>    n.wal.Append(Entry{Op: &quot;PUT&quot;, Key: key, Value: value})<br>    n.wal.Sync()  // fsync to disk<br>    <br>    // 2. Then update memory<br>    n.memory[key] = value<br>    <br>    return nil<br>}<br><br>// On crash recovery<br>func (n *Node) Recover() {<br>    entries := n.wal.ReadAll()<br>    for _, entry := range entries {<br>        n.memory[entry.Key] = entry.Value  // Replay<br>    }<br>}</pre><p><strong>Why this matters</strong>: Node crashes don’t lose data. WAL is on disk, memory is rebuilt from WAL.</p><h3>Rate Limiting (Token Bucket)</h3><pre>// Simplified token bucket<br>type RateLimiter struct {<br>    tokens     float64  // Current tokens<br>    maxTokens  float64  // Burst capacity (10)<br>    refillRate float64  // Tokens/sec (1.67 for 100/min)<br>    lastRefill time.Time<br>}<br><br>func (rl *RateLimiter) Allow() bool {<br>    // Add tokens based on time elapsed<br>    elapsed := time.Since(rl.lastRefill).Seconds()<br>    rl.tokens = min(rl.maxTokens, rl.tokens + elapsed*rl.refillRate)<br>    rl.lastRefill = time.Now()<br>    <br>    // Check and consume<br>    if rl.tokens &gt;= 1.0 {<br>        rl.tokens -= 1.0<br>        return true<br>    }<br>    return false  // Rate limited<br>}</pre><p><strong>Per-user limits</strong>: 100 req/min sustained, burst of 10. Prevents abuse without killing legitimate users.</p><h3>Why This Beats Existing Solutions</h3><h3>vs Redis</h3><ul><li><strong>Redis</strong>: Manual cluster setup, complex resharding, single consistency mode</li><li><strong>dht</strong>: Auto-sharding, dual consistency, web dashboard included</li></ul><h3>vs DynamoDB</h3><ul><li><strong>DynamoDB</strong>: Complex pricing, AWS lock-in, steep learning curve</li><li><strong>dht</strong>: Self-hosted [ free if we do it :) ], simple API, 5-minute setup</li></ul><h3>vs Cloudflare KV</h3><ul><li><strong>CF KV</strong>: Eventual only, vendor lock-in, 60-second write propagation</li><li><strong>dht</strong>: Both modes, open source, ~100ms propagation</li></ul><h3>Performance: The Numbers</h3><p>Local testing (3 nodes, MacBook M1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*ONjGkqJbVRKdMb91qoBflg.jpeg" /></figure><p><strong>Why strong is slower</strong>: Has to wait for 2/3 replicas to ACK.</p><h3><strong>What’s next?</strong></h3><p>This is <strong>100% open source</strong> (MIT License). I built it to learn, and I hope it helps you learn too.</p><p><strong>Looking for contributors!</strong> Whether you want to:</p><ul><li>Add features (Raft consensus, encryption, range queries etc.)</li><li>Fix bugs (there are definitely bugs)</li><li>Improve docs (always needed)</li><li>Build example projects (show me cool use cases!)</li></ul><p>…PRs and issues are welcome! 🙏</p><p>If this interests you, check out the <a href="https://github.com/retr0-kernel/dht">GitHub repo</a>, star it ⭐, try it out, break it, and let me know what you think!</p><h3>Conclusion</h3><p>Started as a weekend frustration with Redis clusters. Ended as a functional distributed KV store with dual consistency modes and a dashboard.</p><p>Is it perfect? Hell no. Is it production-ready for Netflix? Probably not. Is it a great learning project and useful for side projects? Absolutely.</p><p>Building <strong>dht</strong> taught me that distributed systems don’t have to be scary. The key insights:</p><ol><li><strong>CAP theorem is a choice, not a constraint</strong> — Let users pick their tradeoff</li><li><strong>Consistent hashing solves distribution</strong> — No manual sharding needed</li><li><strong>Developer experience matters</strong> — Beautiful dashboard &gt; feature bloat</li><li><strong>Start simple, add complexity only when needed</strong> — WAL, replication, then optimize</li></ol><h3>References</h3><ol><li><a href="https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf">Dynamo: Amazon’s Highly Available Key-value Store</a> &gt; Eventual consistency inspiration</li><li><a href="https://www.akamai.com/site/en/documents/research-paper/consistent-hashing-and-random-trees-distributed-caching-protocols-for-relieving-hot-spots-on-the-world-wide-web-technical-publication.pdf">Consistent Hashing and Random Trees</a> &gt; The hash ring algorithm</li><li><a href="https://mwhittaker.github.io/blog/an_illustrated_proof_of_the_cap_theorem/">CAP Theorem Explained</a> &gt; Why you can’t have it all</li><li><a href="https://www.cs.umd.edu/~abadi/papers/abadi-pacelc.pdf">PACELC Theorem</a> &gt; CAP extended to normal operation</li><li><a href="https://www.postgresql.org/docs/current/warm-standby.html">Understanding Replication</a> &gt; Replication :)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=958bf00525da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalability : Basics]]></title>
            <link>https://medium.com/@krizzsrivastava/scalability-basics-27d291b5f4c5?source=rss-30c8ba8983ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d291b5f4c5</guid>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Krish Srivastava]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 11:28:41 GMT</pubDate>
            <atom:updated>2025-04-05T11:28:41.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*C1B_4tr7RR1HljCF_GULlQ.png" /><figcaption>Scalability</figcaption></figure><h3>Scalability : Basics</h3><p>Making a web service scalable is a tough and hefty task. Here are some parts for basic understanding.</p><h3>Part 1 : Cloning</h3><p>Public servers of any web-service that is scalable are hidden behing the <strong>load balancer.</strong> This load balancer servers evenly distributes load on servers.</p><p>Steve should always get the same results of his request back, independent what server he “landed on”. That leads to the first golden rule for scalability: every server contains exactly the same codebase and does not store any user-related data, like sessions or profile pictures, on local disc or memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFQkLaNmHbENOdmsMnmwQg.png" /></figure><p>Sessions need to be stored in a centralized data store which is accessible to all your application servers. It can be an external database or an external persistent cache, like Redis. An external persistent cache will have better performance than an external database. By external I mean that the data store does not reside on the application servers. Instead, it is somewhere in or near the data center of your application servers.</p><blockquote><strong>But what about deployment then? How can you make sure that a code change is sent to all your servers without one server still serving old code?</strong></blockquote><p>This tricky problem is fortunately already solved by the great tool <strong>Capistrano</strong>. It requires some learning</p><p>After <strong>outsourcing</strong> your sessions and serving the same codebase from all your servers, you can now create an image file from one of these servers (AWS calls this AMI — Amazon Machine Image.) Use this AMI as a “super-clone” that all your new instances are based upon. Whenever you start a new instance/clone, just do an initial deployment of your latest code and you are ready!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUd5M3MDXCT04kUh6dEKGg.png" /></figure><h3>Part 2: Database</h3><p>After Part 1, my servers are now horizontally scaled and they can serve thousands of concurrent requests. But down the road my application will get slower and slower and would finally break down. The reason being my <strong>database</strong>.</p><h4>Path 1:</h4><ul><li>Master-Slave Replication (read from slaves, write to master)</li><li>Upgrade master server by adding RAM</li><li>Sharding</li><li>Denormalization</li><li>Tuning</li></ul><h4>Path 2:</h4><ul><li>Denormalize right from the beginning and include no more joins in any DB query.</li><li>Joins will now need to done in application code.</li></ul><p>But even with doing all of these and even switching to the latest and greatest NoSQL DB and let all your joins through application, soon your DB requests will again be slower and slower. That is where cache comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5SsDTnauTL55SSBdBHBDg.png" /></figure><h3>Part 3: Cache</h3><p>So after part 2, now we have a scalable DB solution. Now we can store terabytes of data and things are fine but just for us. My users still have to suffer slow page requests when a lot of data is fetched from DB. The solution to this implementation of <strong>cache. </strong>By cache, I mean <strong>in-memory caches </strong>like <a href="https://memcached.org/"><strong>Memcached</strong></a> or <a href="https://redis.io/"><strong>Redis</strong></a>.</p><blockquote>Never<strong> </strong>do <strong>file-based caching</strong>, it makes cloning and auto-scaling of your servers just a pain.</blockquote><p>But back to in-memory caches. A cache is a simple key-value store and it should reside as a buffering layer between your application and your data storage. Whenever your application has to read data it should at first try to retrieve the data from your cache. Only if it’s not in the cache should it then try to get the data from the main data source.</p><p>Why should we do that? Because <strong>a cache is lightning-fast</strong>. It holds every dataset in RAM and requests are handled as fast as technically possible. For example, Redis can do several hundreds of thousands of read operations per second when being hosted on a standard server. Also writes, especially increments, are very, very fast.</p><p>There are two patterns of caching data. An old and a new one.</p><ol><li><strong>Cached Database Queries:<br></strong>That’s still the most commonly used caching pattern. Whenever you do a query to your database, you store the result dataset in cache. A hashed version of your query is the cache key. The next time you run the query, you first check if it is already in the cache. The next time you run the query, you check at first the cache if there is already a result. This pattern has several issues. The main issue is the expiration. It is hard to delete a cached result when you cache a complex query. When one piece of data changes (for example a table cell) you need to delete all cached queries who may include that table cell.</li><li><strong>Cached Objects:</strong></li></ol><ul><li>That’s my strong recommendation and I always prefer this pattern. In general, see your data as an object like you already do in your code (classes, instances, etc.). Let your class assemble a dataset from your database and then store the complete instance of the class or the assembed dataset in the cache. Sounds theoretical, I know, but just look how you normally code. You have, for example, a class called “Product” which has a property called “data”. It is an array containing prices, texts, pictures, and customer reviews of your product. The property “data” is filled by several methods in the class doing several database requests which are hard to cache, since many things relate to each other. Now, do the following: when your class has finished the “assembling” of the data array, directly store the data array, or better yet the complete instance of the class, in the cache! This allows you to easily get rid of the object whenever something did change and makes the overall operation of your code faster and more logical.</li><li>It makes asynchronous processing possible! Just imagine an army of worker servers who assemble your objects for you! The application just consumes the latest cached object and nearly never touches the databases anymore!</li></ul><p>Some ideas of objects to cache:</p><ul><li>user sessions (never use the DB!)</li><li>fully rendered blog articles</li><li>activity streams</li><li>user&lt;-&gt;friend relationships</li></ul><h3>Part 4: Asynchronism</h3><p>Imagine you went to eat your favourite <a href="https://en.wikipedia.org/wiki/naan?variant=zh-tw"><em>naan</em></a> at your favourite restaurant. You ask for it, but there is no <a href="https://en.wikipedia.org/wiki/Atta_(flour)#:~:text=Atta%20is%20a%20type%20of,used%20to%20make%20local%20flatbreads.&amp;text=It%20is%20the%20most%20widespread%20flour%20in%20the%20Indian%20subcontinent."><em>aata</em></a>. Instead you are asked to come back in 2 hours when your ordered <a href="https://en.wikipedia.org/wiki/naan?variant=zh-tw"><em>naan</em></a> is ready. That’s annoying, isn’t it?</p><p>To avoid such a “please wait a while” — situation, asynchronism needs to be done. And what’s good for a restaurant, is maybe also good for your web service or web app.</p><p>In general, there are two ways / paradigms asynchronism can be done.</p><ol><li><strong>Async #1:</strong></li></ol><ul><li>Let’s stay in the former restaurant picture. The first way of async processing is the “make the aata ready at night and then sell in the morning” way. No waiting time at the cash register and a happy customer. Referring to a web app this means doing the time-consuming work in advance and serving the finished work with a low request time.</li><li>Very often this paradigm is used to turn dynamic content into static content. Pages of a website, maybe built with a massive framework or CMS, are pre-rendered and locally stored as static HTML files on every change. Often these computing tasks are done on a regular basis, maybe by a script which is called every hour by a cronjob. This pre-computing of overall general data can extremely improve websites and web apps and makes them very scalable and performant. Just imagine the scalability of your website if the script would upload these pre-rendered HTML pages to AWS S3 or Cloudfront or another Content Delivery Network! Your website would be super responsive and could handle millions of visitors per hour!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*J4jgfnbGL0vpv_DVE7z-8g.png" /></figure><ol><li><strong>Async #2:</strong></li></ol><ul><li>Back to the bakery. Unfortunately, sometimes customers has special requests like a birthday cake with “Happy Birthday, Steve!” on it. The bakery can not foresee these kind of customer wishes, so it must start the task when the customer is in the bakery and tell him to come back at the next day. Refering to a web service that means to handle tasks asynchronously.<br>Here is a typical workflow:</li><li>A user comes to your website and starts a very computing intensive task which would take several minutes to finish. So the frontend of your website sends a job onto a job queue and immediately signals back to the user: your job is in work, please continue to the browse the page. The job queue is constantly checked by a bunch of workers for new jobs. If there is a new job then the worker does the job and after some minutes sends a signal that the job was done. The frontend, which constantly checks for new “job is done” — signals, sees that the job was done and informs the user about it. Now that was a very simplified example.</li><li>The basic idea is to have a queue of tasks or jobs that a worker can process. Asynchronism seems complicated, but it is definitely worthy. Backends become nearly infinitely scalable and frontends become snappy which is good for the overall user experience.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXqCE9wB1Bzk9gvax4eiiA.png" /></figure><blockquote>If you do something time-consuming, try to do it always asynchronously.</blockquote><h3>Conclusion</h3><p>The journey to building a scalable web service requires addressing multiple layers of the application stack:</p><ol><li><strong>Horizontal Server Scaling</strong>: By implementing server cloning with identical codebases behind a load balancer, and centralizing user data in external stores, we can effectively distribute user load across multiple servers.</li><li><strong>Database Optimization</strong>: As traffic increases, database performance becomes critical. Whether following the progressive optimization path or denormalizing from the start, the goal is to minimize complex queries and distribute data efficiently.</li><li><strong>Strategic Caching</strong>: Implementing in-memory caching, particularly object caching, creates a vital buffer between application and database, dramatically improving response times and reducing database load.</li><li><strong>Asynchronous Processing</strong>: By either pre-computing content or implementing job queues, we can handle time-consuming tasks without blocking user interactions, creating a responsive experience regardless of backend processing needs.</li></ol><p>These four pillars work together to create a comprehensive scalability strategy that evolves with growing user demands. The most scalable architectures don’t just optimize individual components but consider how they interact as a cohesive system. Remember that scalability is not a one-time achievement but an ongoing process that requires continuous monitoring, testing, and refinement as your service grows.</p><p>Ultimately, the best scalable architecture is one that remains invisible to users, providing consistent performance even as demand increases exponentially.</p><h3>References:</h3><ul><li><a href="https://web.archive.org/web/20221030091841/http://www.lecloud.net/tagged/scalability/chrono">https://web.archive.org/web/20221030091841/http://www.lecloud.net/tagged/scalability/chrono</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d291b5f4c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database 101 : Storage and Retrieval (Part 1)]]></title>
            <link>https://medium.com/@krizzsrivastava/database-101-storage-and-retrieval-part-1-51113a9891e7?source=rss-30c8ba8983ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/51113a9891e7</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[log-structured]]></category>
            <category><![CDATA[data-intensive-system]]></category>
            <dc:creator><![CDATA[Krish Srivastava]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 14:08:27 GMT</pubDate>
            <atom:updated>2025-03-01T15:13:19.511Z</atom:updated>
            <content:encoded><![CDATA[<h3>Database 101 : Storage and Retrieval (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zCmyfNiLLjNjJO2d" /></figure><p>On the most fundamental level, a database needs to do two things: when you give it some data, it should store the data, and when you ask it again later, it should give the data back to you.</p><p>In this part, we discuss the database’s point of view: how we can store the data that we’re given, and how we can find it again when we’re asked for it.</p><h4>Data Structures that Powers the Database</h4><p>We consider a database as two bash functions</p><pre>#!/bin/bash<br>db_set () {<br> echo &quot;$1,$2&quot; &gt;&gt; database<br>}<br>db_get () {<br> grep &quot;^$1,&quot; database | sed -e &quot;s/^$1,//&quot; | tail -n 1<br>}</pre><p>These two functions implement a key-value store. We can call <strong>db_set key value</strong>, which will store <strong>key</strong> and <strong>value</strong> in the database. The key and value can be (almost) anything you like — for example, the value could be a JSON document. You can then call <strong>db_get key</strong>, which looks up the most recent value associated with that particular key and returns it. And it works:</p><pre>$ db_set 123456 &#39;{&quot;name&quot;:&quot;London&quot;,&quot;attractions&quot;:[&quot;Big Ben&quot;,&quot;London Eye&quot;]}&#39;<br><br>$ db_set 42 &#39;{&quot;name&quot;:&quot;San Francisco&quot;,&quot;attractions&quot;:[&quot;Golden Gate Bridge&quot;]}&#39;<br><br>$ db_get 42<br>{&quot;name&quot;:&quot;San Francisco&quot;,&quot;attractions&quot;:[&quot;Golden Gate Bridge&quot;]}</pre><p>The underlying storage format is very simple: a text file where each line contains a key-value pair, separated by a comma (roughly like a CSV file, ignoring escaping issues). Every call to <strong>db_set</strong> appends to the end of the file, so if you update a key several times, the old versions of the value are not overwritten — you need to look at the last occurrence of a key in a file to find the latest value (hence the tail -n 1 in <strong>db_get</strong>):</p><pre>$ db_set 42 &#39;{&quot;name&quot;:&quot;San Francisco&quot;,&quot;attractions&quot;:[&quot;Exploratorium&quot;]}&#39;<br><br>$ db_get 42<br>{&quot;name&quot;:&quot;San Francisco&quot;,&quot;attractions&quot;:[&quot;Exploratorium&quot;]}<br><br>$ cat database<br>123456,{&quot;name&quot;:&quot;London&quot;,&quot;attractions&quot;:[&quot;Big Ben&quot;,&quot;London Eye&quot;]}<br>42,{&quot;name&quot;:&quot;San Francisco&quot;,&quot;attractions&quot;:[&quot;Golden Gate Bridge&quot;]}<br>42,{&quot;name&quot;:&quot;San Francisco&quot;,&quot;attractions&quot;:[&quot;Exploratorium&quot;]}</pre><p>We can see that the <strong>db_set</strong> function has pretty good performance for something which is so simple, because appending to a file is generally very efficient. Similarly to what <strong>db_set</strong> does, many databases internally use a log, which is an append-only data file. Real databases have more issues to deal with (such as concurrency control, reclaim‐ ing disk space so that the log doesn’t grow forever, and handling errors and partially written records), but the basic principle is the same.</p><p>On the other hand, our <strong>db_get</strong> function has terrible performance if you have a large number of records in your database. Every time you want to look up a key, <strong>db_get</strong> has to scan the entire database file from beginning to end, looking for occurrences of the key. In algorithmic terms, the cost of a lookup is <strong>O(n)</strong>: if you double the number of records <strong>n</strong> in your database, a lookup takes twice as long. That’s not good.</p><p>Now here comes the concept of <strong>indexes</strong>. In order to efficiently find the value for a particular key in the database, we need a different data structure: an <strong>index</strong>.</p><blockquote>The general idea behind indexes is to keep some additional metadata on the side, which acts as a signpost and helps you to locate the data you want.</blockquote><p>An index is an <em>additional</em> structure that is derived from the primary data. Many data‐ bases allow you to add and remove indexes, and this doesn’t affect the contents of the database; it only affects the performance of queries. Maintaining additional structures incurs overhead, especially on writes. For writes, it’s hard to beat the performance of simply appending to a file, because that’s the simplest possible write operation. Any kind of index usually slows down writes, because the index also needs to be updated every time data is written.</p><p>This is an important trade-off in storage systems: well-chosen indexes speed up read queries, but every index slows down writes. For this reason, databases don’t usually index everything by default, but requires — the application developer or database administrator — to choose indexes manually, using one’s knowledge of the application’s typical query patterns. We can then choose the indexes that give your application the greatest benefit, without introducing more overhead than necessary</p><h4>Hash Indexes</h4><p>Let’s start with indexes for key-value data. It is not the only kind of data we can index but its very common and it’s a building block for more complex indexes. They are very similar to the <em>dictionary </em>type, which is usually implemented using a hash map (hash table). One question that you may ask is, Since we already have hash maps for our inmemory data structures, why not use them to index our data on disk?</p><p>Let’s say our data storage consists only of appending to a file. Then the simplest possible indexing strategy is this: keep an in-memory hash map where every key is mapped to a byte offset in the data file — the location at which the value can be found, as in Figure 1. Whenever you append a new key-value pair to the file, you also update the hash map to reflect the offset of the data you just wrote (this works both for inserting new keys and for updating existing keys). When you want to look up a value, use the hash map to find the offset in the data file, seek to that location, and read the value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vQ3fBHo4cYp7iXMJ8OqWQ.png" /><figcaption>Storing a log of key-value pairs in a CSV-like format, indexed with an in-memory hash map.</figcaption></figure><p>This may sound simplistic, but it is a viable approach. In fact, this is essentially what Bitcask (the default storage engine in <a href="https://riak.com/about/">Riak</a>) does. Bitcask offers high-performance reads and writes, subject to the requirement that all the keys fit in the available RAM, since the hash map is kept completely in-memory. The values can use more space than there is available memory, since they can be loaded from disk with just one disk seek. If that part of the data file is already in the filesystem cache, a read doesn’t require any disk I/O at all. A storage engine like Bitcask is well suited for usecases where the value for each key is frequently updated. For example, the key might be the URL of a cat video, and the value might be the number of times it has been played (incremented every time someone hits the play button). In this kind of workload, there are a lot of writes, but there are not too many distinct keys — we have a large number of writes per key, but it’s feasible to keep all keys in memory.</p><p>One disadvantage that even you may have noticed is, that we only append to a file — so how do we avoid eventually running out of disk space?</p><p>A good solution is to break the log into segments of a cer‐ tain size by closing a segment file when it reaches a certain size, and making subse‐ quent writes to a new segment file. This can be done using <strong>compaction. </strong>(Figure 2)</p><blockquote>Compaction means throwing away duplicate keys in the log, and keeping only the most recent update for each key.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Te0thJtWsIPU8PPKNj-STg.png" /><figcaption>Compaction of a key-value update log (counting the number of times each cat video was played), retaining only the most recent value for each key.</figcaption></figure><p>We can also combine many segments at the same time as compaction, as illustrated in Figure 3, since compaction frequently reduces segments significantly (assuming that a key is rewritten multiple times on average within one segment). The merged segment is written to a new file because segments are never changed once they are written. We can use the old segment files to service read and write requests normally while the merging and compaction of frozen segments is being done in a background thread. The old segment files can then be destroyed once the merging procedure is finished. Read requests are then changed to use the newly combined segment rather than the old segments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-Wrvr0FYq1CeJ6HY3nMhg.png" /><figcaption>Performing compaction and segment merging simultaneously.</figcaption></figure><p>Each segment maintains its own hash table in memory, creating a mapping between keys and their corresponding file offsets. When searching for a specific key’s value, the system begins by examining the hash map of the most recent segment. If the key isn’t found there, it proceeds to check the second-most-recent segment, continuing this pattern until the key is located. Through an efficient merging process, the system keeps the number of segments manageable, preventing lookups from having to traverse numerous hash maps.</p><p>While this concept appears straightforward, implementing it effectively requires addressing several practical challenges:</p><h4>Optimized File Format</h4><p>CSV isn’t ideal for log-structured storage. A binary format proves more efficient and less complex, typically encoding the string length in bytes first, followed by the raw string data without requiring escape characters.</p><h4>Record Deletion Mechanism</h4><p>To remove a key and its value, you don’t delete existing data but instead append a special deletion record (known as a <a href="https://docs.datastax.com/en/dse/6.9/architecture/database-internals/architecture-tombstones.html"><strong>tombstone</strong></a>) to the data file. During segment merging operations, these tombstones signal the system to discard any previous values associated with the deleted keys.</p><h4>Effective Crash Recovery</h4><p>When the database restarts, in-memory hash maps are lost. While you could theoretically reconstruct each segment’s hash map by reading entire segment files and tracking the most recent offsets for every key, this approach would be time-consuming for large segments. Systems like Bitcask solve this by storing snapshots of segment hash maps on disk, allowing faster recovery.</p><h4>Handling Partial Writes</h4><p>Database crashes may occur during record appending operations. To address this, implementations often include checksums within files, enabling detection and exclusion of corrupted log sections.</p><h4>Concurrency Management</h4><p>Since writes append to the log in sequential order, many implementations use a single writer thread. Because data file segments are append-only and otherwise immutable, they support concurrent reading by multiple threads without conflict.</p><p>While initially appearing wasteful compared to in-place updates, the append-only approach offers significant benefits:</p><ul><li>Sequential write operations (appending and segment merging) significantly outperform random writes, particularly on magnetic hard drives and even on SSDs to some extent.</li><li>Immutable or append-only segment files greatly simplify concurrency handling and crash recovery. You avoid scenarios where crashes during value overwriting leave files with partially old and new values.</li><li>The segment merging process naturally prevents data file fragmentation over time.</li></ul><h3>Limitations</h3><p>Despite its advantages, this approach has important constraints:</p><ul><li>The entire hash table must fit in memory. With extremely large key sets, this becomes problematic. While theoretically possible to maintain hash maps on disk, such implementations suffer from performance issues due to random I/O requirements, expensive growth operations, and complex collision handling.</li><li>Range queries perform poorly. For example, scanning all keys in a specific range (like “kitty00000” to “kitty99999”) would require individually looking up each key in the hash maps rather than performing an efficient range scan.</li></ul><p>In the next section, we will explore about SSTables and LSM-Tress, an indexing structure that addresses these limitations.</p><p>These notes reflect my understanding from reading “<a href="https://g.co/kgs/yV1SHzE">Designing Data-Intensive Applications</a>” by Martin Kleppmann. His explanations of log-structured storage systems, with their append-only design and hash table indexing, demonstrate important trade-offs in database architecture that I’ve documented here for reference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51113a9891e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Containers From the Ground Up: My Journey Into Containers from Scratch]]></title>
            <link>https://medium.com/@krizzsrivastava/understanding-containers-from-the-ground-up-my-journey-into-containers-from-scratch-8f3651cdb320?source=rss-30c8ba8983ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f3651cdb320</guid>
            <category><![CDATA[computer-security]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Krish Srivastava]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 12:57:52 GMT</pubDate>
            <atom:updated>2025-02-15T12:58:36.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*so07WPUEFFKw3_nTqyQ2Mg.png" /></figure><p>When we run docker run or deploy containers in Kubernetes, we&#39;re often abstracting away the fascinating internals that make containers work. After diving deep into Eric Chiang&#39;s excellent &quot;<a href="https://ericchiang.github.io/post/containers-from-scratch/">Containers from Scratch</a>&quot; writeup, I decided to explore these concepts myself to truly understand what happens under the hood.</p><p>Eric mentioned that while containers are often compared to lightweight virtual machines, they’re actually something much more fundamental: isolated groups of processes running on a single host. This isolation isn’t magic — it’s built on several powerful features baked right into the Linux kernel: namespaces, cgroups, chroots, and other mechanisms you may have heard of but never fully explored.</p><p>Instead of treating containers as a black box, let’s peel back the layers and build our own containers from these fundamental building blocks.</p><p>We will cover:</p><ul><li>setting up a file system</li><li>chroot</li><li>unshare</li><li>nsenter</li><li>bind mounts</li><li>cgroups</li><li>capabilities</li></ul><h3>Setting Up a File System</h3><h4>The Basics:</h4><p>When we think of container images, we often imagine complex structures. But at their core, container images are remarkably simple or as Eric said, they’re just tarballs (or sometimes tarballs within tarballs, if you’re dealing with more sophisticated setups). This simplicity is key to understanding how containers work.</p><h4>Setting Up Our Playground:</h4><p>Let’s start by downloading and verifying our filesystem,</p><pre>$ wget https://github.com/ericchiang/containers-from-scratch/releases/download/v0.1.0/rootfs.tar.gz<br>$ sha256sum rootfs.tar.gz <br>c79bfb46b9cf842055761a49161831aee8f4e667ad9e84ab57ab324a49bc828c  rootfs.tar.gz</pre><p><strong>NOTE</strong> — If you cannot use wget , you can also try,</p><pre>$ curl -L -O https://github.com/ericchiang/containers-from-scratch/releases/download/v0.1.0/rootfs.tar.gz</pre><h4>Exploring the Container Filesystem:</h4><p>Now, let’s extract the tarball and examine its contents:</p><pre>$ sudo tar -zxf rootfs.tar.gz<br>$ ls rootfs<br>bin   dev  home  lib64  mnt  proc  run   srv  tmp  var<br>boot  etc  lib   media  opt  root  sbin  sys  usr<br>$ ls -al rootfs/bin/ls<br>-rwxr-xr-x. 1 root root 118280 Feb 15  2025 rootfs/bin/ls</pre><p>What we see here is fascinating — it’s essentially a complete Linux filesystem hierarchy. We have all the standard directories you’d expect to find in a Linux system:</p><ul><li>/bin for essential command binaries</li><li>/etc for system configuration files</li><li>/lib for fundamental shared libraries</li><li>And all the other standard Linux filesystem components</li></ul><p>While the process of creating these base filesystem tarballs is interesting in its own right, we’ll focus on using this filesystem for our container experiments. For those interested in the image creation process, I recommend checking out the talk “<a href="https://www.youtube.com/watch?v=gMpldbcMHuI">Minimal Containers</a>” by <strong>Brian Redbeard</strong>, which dives deep into that topic.</p><h3>chroot</h3><h4>What is chroot</h4><p>chroot (change root) is one of the most fundamental tools in our container-building journey. It&#39;s a simple yet powerful command that changes the apparent root directory for a running process. Think of it as creating a jail where a process can only see and access files within a specified directory.</p><p>Let’s start by creating a basic isolated environment using our previously extracted filesystem:</p><pre>$ sudo chroot rootfs /bin/bash<br>root@localhost:/ ls /<br>bin   dev  home  lib64  mnt  proc  run   srv  tmp  var<br>boot  etc  lib   media  opt  root  sbin  sys  usr<br>root@localhost:/ which python<br>/usr/bin/python<br>root@localhost:/ /usr/bin/python -c &#39;print &quot;Hello, container world!&quot;&#39;<br>Hello, container world!</pre><p>What makes this work is fascinating — when we run Python inside our chroot environment, we’re actually executing rootfs/usr/bin/python, not the Python interpreter from our host system. This works because our tarball includes:</p><ul><li>The Python binary itself</li><li>All necessary shared libraries</li><li>Required device files and system configurations</li></ul><h4>Beyond the Shell: Running Applications</h4><p>We can do more than just run a shell — let’s start a simple web server in our chrooted environment:</p><pre>$ sudo chroot rootfs python -m SimpleHTTPServer<br>Serving HTTP on 0.0.0.0 port 8000 ...</pre><p>If you try this yourself, you can access the server at <a href="http://localhost:8000/">http://localhost:8000/</a> — it will serve files from within our contained environment.</p><p>Network services still work normally, as chroot only affects filesystem visibility</p><h3>Unshare</h3><h4>The Limitations of chroot</h4><pre># outside of the chroot<br>$ top</pre><p>From inside our chroot, we can still see and interact with host processes:</p><pre>$ sudo chroot rootfs /bin/bash<br>root@localhost: mount -t proc proc /proc<br>root@localhost: ps aux | grep top<br>1000     24753  0.1  0.0 156636  4404 ?        S+   22:28   0:00 top<br>root     24764  0.0  0.0  11132   948 ?        S+   22:29   0:00 grep top</pre><p>Even more concerning, since we’re running as root, we can affect host processes:</p><pre>root@localhost:/ pkill top</pre><p>This demonstrates a critical security issue — our “contained” process can still see and interact with the host system’s processes.</p><h4>Namespaces</h4><p>This is where Linux namespaces come into play. Namespaces provide isolated views of various system aspects, including:</p><ul><li>Process IDs (PID)</li><li>Network interfaces</li><li>Mount points</li><li>User IDs</li><li>And more</li></ul><h4>Creating a PID Namespace</h4><p>Let’s create a truly isolated environment using <a href="https://linux.die.net/man/2/unshare">unshare</a>:</p><pre>$ sudo unshare -p -f --mount-proc=$PWD/rootfs/proc \<br>    chroot rootfs /bin/bash<br>root@localhost:/ ps aux<br>USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND<br>root         1  0.0  0.0  20268  3240 ?        S    22:34   0:00 /bin/bash<br>root         2  0.0  0.0  17504  2096 ?        R+   22:34   0:00 ps aux</pre><ul><li>unshare -p: Creates a new PID namespace</li><li>-f: Forks a new process</li><li>--mount-proc=$PWD/rootfs/proc: Mounts a new procfs for our namespace</li><li>chroot rootfs /bin/bash: Changes root and starts a shell</li></ul><p>Funny thing is, our shell now has PID 1 — this is significant because in Linux, PID 1 is usually reserved for the init system. Also we can no longer see host processes — true process isolation!</p><p>This is much closer to what happens in real containers.</p><p>This isolation is a crucial step toward building real containers — it prevents processes inside the container from interfering with host processes, a key security feature.</p><h3>nsenter</h3><p>One of the most powerful aspects of Linux namespaces is their <strong>composability</strong> — processes can isolate certain namespaces while sharing others. For example, two programs might use separate PID namespaces while sharing the same network namespace (a common scenario in <strong>Kubernetes pods</strong>). This is where the <a href="https://linux.die.net/man/2/setns">setns</a><strong> </strong>syscall and the nsenter command-line tool come into play.</p><h4>Identifying the Namespace of a Process</h4><p>Let’s locate a shell running inside a chroot environment from our previous example:</p><pre># Run this from the host system (outside the chroot)<br>$ ps aux | grep /bin/bash | grep root<br>...<br>root     29840  0.0  0.0  20272  3064 pts/5    S+   17:25   0:00 /bin/bash</pre><p>The Linux kernel exposes namespace information via /proc/(PID)/ns/. To inspect the namespaces of PID 29840, we can list the namespace files:</p><pre>$ sudo ls -l /proc/29840/ns<br>total 0<br>lrwxrwxrwx. 1 root root 0 Oct 15 17:31 ipc -&gt; &#39;ipc:[4026531839]&#39;<br>lrwxrwxrwx. 1 root root 0 Oct 15 17:31 mnt -&gt; &#39;mnt:[4026532434]&#39;<br>lrwxrwxrwx. 1 root root 0 Oct 15 17:31 net -&gt; &#39;net:[4026531969]&#39;<br>lrwxrwxrwx. 1 root root 0 Oct 15 17:31 pid -&gt; &#39;pid:[4026532446]&#39;<br>lrwxrwxrwx. 1 root root 0 Oct 15 17:31 user -&gt; &#39;user:[4026531837]&#39;<br>lrwxrwxrwx. 1 root root 0 Oct 15 17:31 uts -&gt; &#39;uts:[4026531838]&#39;</pre><p>Here, /proc/29840/ns/pid represents the <strong>PID namespace</strong> we want to join.</p><h4>Using nsenter to Enter a Namespace</h4><p>The nsenter command allows us to enter an existing namespace instead of creating a new one. We can use it to join the PID namespace of <strong>PID 29840</strong>:</p><pre>$ sudo nsenter --pid=/proc/29840/ns/pid \<br>    unshare -f --mount-proc=$PWD/rootfs/proc \<br>    chroot rootfs /bin/bash</pre><ul><li>nsenter --pid=/proc/29840/ns/pid → Joins the process&#39;s PID namespace.</li><li>unshare -f --mount-proc=$PWD/rootfs/proc → Remounts /proc to reflect the new PID namespace.</li><li>chroot rootfs /bin/bash → Changes the root directory to rootfs and launches a new shell.</li></ul><h4>Verifying the Namespace Entry</h4><p>Once inside, we can check running processes:</p><pre>root@localhost:/ ps aux<br>USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND<br>root         1  0.0  0.0  20272  3064 ?        S+   00:25   0:00 /bin/bash<br>root         5  0.0  0.0  20276  3248 ?        S    00:29   0:00 /bin/bash<br>root         6  0.0  0.0  17504  1984 ?        R+   00:30   0:00 ps aux</pre><p>Here, the new shell (PID 5) now sees the original shell (PID 1), confirming that we have successfully entered the namespace.</p><h3>Bind Mounts</h3><p>When working with immutable containers, there are times when we need to inject files or directories into the chroot environment. This is particularly useful for storage, configuration, or sharing d ata between the host and the containerized environment.</p><p>A common way to achieve this is by using bind mounts, which allow us to map directories from the host into a chrooted environment. Bind mounts behave like advanced symlinks, but unlike symbolic links, they integrate the filesystem directly at the kernel level.</p><h4>Creating a Read-Only Mount Inside a Chroot</h4><p>First, we create a directory and a file on the host:</p><pre>$ sudo mkdir readonlyfiles<br>$ echo &quot;hello&quot; &gt; readonlyfiles/hi.txt</pre><p>Next, we create a corresponding directory inside the chroot environment and mount the host directory as read-only (-o ro):</p><pre>$ sudo mkdir -p rootfs/var/readonlyfiles<br>$ sudo mount --bind -o ro $PWD/readonlyfiles $PWD/rootfs/var/readonlyfiles</pre><p>This allows the chroot-ed process to access readonlyfiles as if it were part of its own filesystem.</p><h4>Accessing the Mounted Files in the Chroot</h4><p>Once inside the chroot, we can read the file:</p><pre>$ sudo chroot rootfs /bin/bash<br>root@localhost:/ cat /var/readonlyfiles/hi.txt<br>hello</pre><p>However, because the mount is read-only, writing to the file fails:</p><pre>root@localhost:/ echo &quot;bye&quot; &gt; /var/readonlyfiles/hi.txt<br>bash: /var/readonlyfiles/hi.txt: Read-only file system</pre><h4>Extending Bind Mounts</h4><p>While this is a basic example, the same technique can be used to mount:</p><ul><li><strong>Network File Systems (NFS)</strong> for shared storage</li><li><strong>In-memory filesystems (tmpfs)</strong> for temporary data</li><li><strong>Other host directories</strong> needed inside the chroot</li></ul><p>To remove the bind mount, use umount (since rm won’t work):</p><pre>$ sudo umount $PWD/rootfs/var/readonlyfiles</pre><h3>cgroups</h3><p><strong>cgroups (control groups)</strong> allow the Linux kernel to <strong>impose resource limits</strong> on processes, such as CPU, memory, and I/O. Without cgroups, isolated processes could still <strong>consume all available resources</strong>, making system isolation ineffective.</p><p>The kernel exposes cgroups through the /sys/fs/cgroup/ directory. If it&#39;s not present, you may need to manually mount the memory cgroup.</p><pre>$ ls /sys/fs/cgroup/<br>blkio  cpuacct      cpuset   freezer  memory   net_cls,net_prio  perf_event  systemd<br>cpu    cpu,cpuacct  devices  hugetlb  net_cls  net_prio          pids</pre><p>For example,</p><h4>Creating a cgroup for Memory Limitation</h4><p>To create a new cgroup, simply create a directory under /sys/fs/cgroup/memory/. The kernel will automatically populate it with files that allow configuration.</p><pre>$ sudo su<br>mkdir /sys/fs/cgroup/memory/demo<br>ls /sys/fs/cgroup/memory/demo/</pre><p>This directory contains files that control memory constraints:</p><pre>cgroup.clone_children               memory.memsw.failcnt<br>cgroup.event_control                memory.memsw.limit_in_bytes<br>cgroup.procs                        memory.memsw.max_usage_in_bytes<br>memory.failcnt                      memory.memsw.usage_in_bytes<br>memory.force_empty                  memory.move_charge_at_immigrate<br>memory.kmem.failcnt                 memory.numa_stat<br>memory.kmem.limit_in_bytes          memory.oom_control<br>memory.kmem.max_usage_in_bytes      memory.pressure_level<br>memory.kmem.slabinfo                memory.soft_limit_in_bytes<br>memory.kmem.tcp.failcnt             memory.stat<br>memory.kmem.tcp.limit_in_bytes      memory.swappiness<br>memory.kmem.tcp.max_usage_in_bytes  memory.usage_in_bytes<br>memory.kmem.tcp.usage_in_bytes      memory.use_hierarchy<br>memory.kmem.usage_in_bytes          notify_on_release<br>memory.limit_in_bytes               tasks<br>memory.max_usage_in_bytes</pre><p>Here is some explanation of what these terms mean,</p><pre>memory.limit_in_bytes               # Maximum memory usage allowed<br>memory.usage_in_bytes               # Current memory usage<br>memory.max_usage_in_bytes           # Peak memory usage<br>memory.swappiness                   # Controls swap usage (0 = no swap)<br>tasks                               # Lists processes assigned to this cgroup</pre><p>To set a memory limit of <strong>100MB</strong> and disable swap:</p><pre>echo &quot;100000000&quot; &gt; /sys/fs/cgroup/memory/demo/memory.limit_in_bytes<br>echo &quot;0&quot; &gt; /sys/fs/cgroup/memory/demo/memory.swappiness</pre><h4>Adding a Process to the cgroup</h4><p>The tasks file determines which processes are managed by the cgroup. To <strong>assign a process</strong>, write its PID into the file.</p><pre># echo $$ &gt; /sys/fs/cgroup/memory/demo/tasks</pre><p>Here, $$ represents the <strong>PID of the current shell</strong>.</p><h4>Testing Memory Restrictions</h4><p>To test if the memory limits work, we run a Python script that gradually consumes memory:</p><pre>f = open(&quot;/dev/urandom&quot;, &quot;r&quot;)<br>data = &quot;&quot;<br><br>i = 0<br>while True:<br>    data += f.read(10000000)  # 10MB chunks<br>    i += 1<br>    print(&quot;%dMB&quot; % (i * 10,))</pre><p>Running it we get,</p><pre># python hungry.py<br>10mb<br>20mb<br>30mb<br>...<br>80mb<br>Killed</pre><p>When the process reaches <strong>100MB</strong>, it gets <strong>killed</strong> by the kernel.</p><h4>Cleaning Up the cgroup</h4><p>Before removing the cgroup, all processes inside it must exit or be reassigned. Once empty, remove the cgroup directory:</p><pre># exit<br>$ sudo rmdir /sys/fs/cgroup/memory/demo</pre><p>Why they matter?</p><ul><li>Prevents a single process from <strong>crashing the system</strong>.</li><li>Allows efficient <strong>resource allocation</strong> in <strong>containers (Docker, Kubernetes, LXC)</strong>.</li><li>Helps in <strong>performance tuning</strong> by restricting CPU/memory usage per process.</li></ul><h3>Capabilities</h3><p>Containers are great for <strong>running arbitrary code</strong> with <strong>low overhead</strong>, but this also makes them easier to <strong>break out of</strong> compared to Virtual Machines (VMs). Since containers often run as <strong>root</strong>, security features like <strong>SELinux, seccomp, and </strong><a href="https://linux.die.net/man/7/capabilities"><strong>Linux capabilities</strong></a> help <strong>limit their privileges</strong> to reduce risk.</p><h4>Understanding Linux Capabilities</h4><p>Instead of granting full <strong>root</strong> privileges to a process, Linux <strong>capabilities</strong> allow fine-grained control over what a process can do.</p><p>For example, consider a <strong>Go program</strong> that tries to listen on <strong>port 80</strong>:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;net&quot;<br>    &quot;os&quot;<br>)<br><br>func main() {<br>    if _, err := net.Listen(&quot;tcp&quot;, &quot;:80&quot;); err != nil {<br>        fmt.Fprintln(os.Stdout, err)<br>        os.Exit(2)<br>    }<br>    fmt.Println(&quot;success&quot;)<br>}</pre><p>If we compile and run it:</p><pre>$ go build -o listen listen.go<br>$ ./listen<br>listen tcp :80: bind: permission denied</pre><p>It <strong>fails</strong> because <strong>binding to ports below 1024 requires special privileges</strong>. Normally, we’d use <strong>sudo</strong>, but we can <strong>grant only the necessary capability</strong> instead.</p><pre>$ sudo setcap cap_net_bind_service=+ep listen<br>$ getcap listen<br>listen = cap_net_bind_service+ep<br>$ ./listen<br>success</pre><p>Now, the binary can bind to <strong>port 80</strong> <strong>without full root access</strong>.</p><h4>Dropping Capabilities in a Root Shell</h4><p>By default, a <strong>root shell</strong> has many capabilities. We can check them using:</p><pre>$ sudo su<br># capsh --print<br>Current: = cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,37+ep<br>Bounding set =cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,37<br>Securebits: 00/0x0/1&#39;b0<br> secure-noroot: no (unlocked)<br> secure-no-suid-fixup: no (unlocked)<br> secure-keep-caps: no (unlocked)<br>uid=0(root)<br>gid=0(root)<br>groups=0(root)</pre><p>This prints a <strong>long list of capabilities</strong> like:</p><ul><li>cap_net_bind_service → Bind to low-numbered ports</li><li>cap_sys_admin → Perform system admin tasks</li><li>cap_chown → Change file ownership</li></ul><p>Instead of <strong>granting</strong> capabilities, we usually want to <strong>remove them</strong> to <strong>reduce risk</strong>.</p><p>Example: Dropping CAP_CHOWN, CAP_SETFPCAP, and CAP_SYS_ADMIN:</p><pre>$ sudo capsh --drop=cap_chown,cap_setpcap,cap_setfcap,cap_sys_admin --chroot=$PWD/rootfs --</pre><p>Inside this shell, we try to change file ownership:</p><pre>root@localhost:/# whoami<br>root<br>root@localhost:/# chown nobody /bin/ls<br>chown: changing ownership of &#39;/bin/ls&#39;: Operation not permitted</pre><p>Even though the process <strong>runs as root</strong>, it <strong>can’t change file ownership</strong> because we removed CAP_CHOWN.</p><p>Even with security measures, <strong>VMs are still more isolated</strong> than containers when running <strong>untrusted code</strong>. However, capabilities, seccomp, and SELinux provide <strong>defense-in-depth</strong> against attacks on containerized applications.</p><h4>Best Practices for Secure Containers:</h4><ul><li>✅ Don’t run containers as root</li><li>✅ Grant only the necessary capabilities (e.g., CAP_NET_BIND_SERVICE)</li><li>✅ Use seccomp and SELinux for additional restrictions</li><li>✅ Regularly update container images to patch vulnerabilities</li><li>✅ Be mindful of linked dependencies</li></ul><h3>Conclusion</h3><p>Containers <strong>aren’t magic</strong> — they are built on <strong>existing Linux features</strong> like namespaces, cgroups, and capabilities. <strong>Understanding these low-level concepts</strong> helps in <strong>debugging and improving security</strong>.</p><p>While <strong>we don’t need to build our own container runtime</strong>, knowing how they work under the hood makes one a <strong>better developer</strong>. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f3651cdb320" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DNS in detail]]></title>
            <link>https://medium.com/@krizzsrivastava/dns-in-detail-9e8369af0ca7?source=rss-30c8ba8983ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e8369af0ca7</guid>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[network]]></category>
            <dc:creator><![CDATA[Krish Srivastava]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 13:05:07 GMT</pubDate>
            <atom:updated>2024-10-28T13:05:07.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ScM6UND921F5Bard" /><figcaption>DNS</figcaption></figure><p>How DNS works and how it helps you access internet services.</p><h3><strong>What is DNS?</strong></h3><p>We can easily communicate with gadgets on the internet without having to remember complicated numbers thanks to <strong>DNS</strong> (Domain Name System). Every computer on the internet has a unique address to connect with it, known as an IP address, just as every home has a unique address for delivering mail straight to it. The following is an example of an IP address: <strong>104.26.10.229</strong>, which consists of four sets of numbers from 0 to 255 separated by a period. DNS is useful because it’s not very convenient to remember this complex string of numbers when you want to access a website. You can therefore remember <strong>example.com</strong> rather than <strong>104.26.10.229</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWl1KwMOHf59tj0I8IVrFw.png" /></figure><h3>Domain Hierarchy?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkB4E3rKfPjZHhcdfMZbbA.png" /></figure><p><strong>TLD (Top-Level Domain)</strong></p><p>The portion at the right of a domain name is called a TLD. The TLD for google.com, for instance, is .com. <strong>gTLD (Generic Top Level)</strong> and <strong>ccTLD (Country Code Top Level Domain)</strong> are the two varieties of TLD. In the past, the purpose of a gTLD was supposed to be clear to the user; for instance, a .com would be used for business, a .org for an organization, a .edu for education, and a .gov for government. Additionally, a ccTLD was used for geographic purposes; for instance, .in was used for sites based in India, .co.uk for sites based in the UK and so forth. As a result of this demand, new gTLDs are popping up, including .online, .club, .website, .biz and many more.</p><p><strong>Second-Level Domain</strong></p><p>Consider medium.com as an example, where medium is the Second Level Domain and the .com portion is the TLD. The second-level domain can only have 63 letters plus the TLD when registering, and it can only contain hyphens and the characters a-z 0–9 (it cannot begin or end with hyphens or occur consecutively).</p><p><strong>Subdomain</strong></p><p>With a period to divide it, a subdomain is located on the left side of the second-level domain; for instance, the admin portion of the name admin.example.com is the subdomain. A subdomain name can only have 63 characters, a-z 0–9, and hyphens (it cannot begin or finish with hyphens or contain consecutive hyphens). These are the same creation restrictions as a second-level domain. You can generate longer names, like alexios.servers.example.com, by using numerous subdomains separated by periods. However, it must be no more than 253 characters long. You are not restricted in how many subdomains you can make for your domain name.</p><h3>DNS Record Types?</h3><p>DNS is not just used for websites, also multiple types of DNS records exist.</p><p><strong>A Record</strong></p><p>These records resolve to IPv4 addresses, for example 106.24.19.235</p><p><strong>AAAA Record</strong></p><p>These records resolve to IPv6 addresses, for example 2544:2500:40::691a:be6</p><p><strong>CNAME Record</strong></p><p>For instance, most online stores have the subdomain name store.name.com, which yields a CNAME record shops.shopify.com. These records redirect to another domain name. The IP address would then be determined by sending shops.shopify.com another DNS request.</p><p><strong>MX Record</strong></p><p>The address of the servers that manage the email for the domain you are accessing is resolved by these records; for instance, an MX record response for example.com would resemble alt1.aspmx.l.google.com. Additionally, these documents have a priority flag. If the primary server fails and emails need to be routed to a backup server, this is ideal because it instructs the client in which order to attempt the servers.</p><p><strong>TXT Record</strong></p><p>Any text-based data can be saved in TXT records, which are free text fields. Among the many applications for TXT records is the listing of servers authorized to send emails on behalf of the domain, which can aid in the fight against spam and spoofing emails. When registering for third-party services, they can also be used to confirm that the domain name belongs to the owner.</p><h3>Making a Request</h3><p><strong><em>What happens when we make a DNS request? Let’s dive into it,</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFVXu8LvGSGv_LwnHzuT-Q.png" /></figure><p>The flow above looks a bit overwhelming so let’s understand it in steps.</p><ol><li>Your computer initially looks through its local cache to determine if you have recently looked up the address when you request a domain name; if not, it will send a request to your Recursive DNS Server.</li><li>Your ISP typically offers a recursive DNS server, but you have the option to select your own. A local cache of recently searched domain names is also available on this server. Your request is terminated here if a local result is found (this is typical for popular and heavily requested services like Google, Facebook, and Twitter). The search for the right response starts with the root DNS servers on the internet if the request cannot be located locally.</li><li>Depending on your request, the root servers — which function as the internet’s DNS backbone — redirect you to the appropriate Top Level Domain Server. When you request, for instance, <a href="http://www.example.com,/">www.example.com,</a> the root server will identify the .com Top Level Domain and direct you to the appropriate TLD server that handles.com addresses.</li><li>The TLD server contains information on where to locate the authoritative server in order to respond to a DNS request. The domain nameserver is another common name for the authoritative server. kip.ns.cloudflare.com and uma.ns.cloudflare.com are the name servers for example.com, for instance. Frequently, a domain name has several nameservers to provide as a fallback in the event that one fails.</li><li>The server in charge of maintaining the DNS records (Authoritative DNS server) for a certain domain name and serving as the location for any updates to your domain name DNS records is known as an authoritative DNS server. The DNS record is then returned to the Recursive DNS Server, where a local copy is cached for upcoming queries and then forwarded back to the initial client that initiated the request, depending on the type of record. Every DNS record has a Time To Live (TTL) value. This value is a number in seconds that indicates how long the response should be stored locally before you need to search for it again. By using caching, you can avoid sending a DNS request each time you interact with a server.</li></ol><h3>Practical Queries</h3><p>For an example <strong>website.htm,</strong></p><ul><li>CNAME of shop.website.htm will be <strong>shops.myshopify.com</strong>,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*CDy64dn1HpiWUDoFiCzqOQ.png" /></figure><ul><li>TXT record of website.htm will be <strong>THM{7012BBA60997F35A9516C2E16D2944FF}</strong>,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*WWMVmE5KhSDFTOWzu_P8DQ.png" /></figure><ul><li>Numerical priority value for the MX record and URL will be <strong>30 alt4.aspmx.l.google.com,</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*KOOalsUYc_ZWCje3cr7wFw.png" /></figure><ul><li>IP address for the A record of <a href="http://www.website.htm/">www.website.htm</a> will be, <strong>10.10.10.10</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*U7OgBTOaOfzKNYPdVPlMRw.png" /></figure><p>In short, DNS is what translates domain names to IP addresses, making it a critical component of the internet backbone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e8369af0ca7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Engineering 101 : Vault Door Training]]></title>
            <link>https://medium.com/@krizzsrivastava/reverse-engineering-101-vault-door-training-293eee761b57?source=rss-30c8ba8983ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/293eee761b57</guid>
            <category><![CDATA[picoctf]]></category>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[decoding]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Krish Srivastava]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 13:54:40 GMT</pubDate>
            <atom:updated>2024-08-17T13:54:40.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reverse Engineering 101 : Vault Door Training</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*0PRj4RktCMoC2VSh.jpg" /><figcaption>Source : <a href="https://zdresearch.com/shop/reverse-engineering/">https://zdresearch.com/shop/reverse-engineering/</a></figcaption></figure><p>The “Vault Door Training” challenge is designed to introduce us to the basics of reverse engineering by analyzing a simple Java program. The goal is to retrieve the flag hidden in the source code by understanding how the program checks for a valid password.</p><h4><strong>Challenge Description</strong></h4><p>We are tasked with entering Dr. Evil’s laboratory to retrieve blueprints for his Doomsday Project. The lab is protected by a series of locked vault doors, each requiring a password to open. Our mission is to figure out the correct password for the first vault door by analyzing the provided source code.</p><h4>Understanding the Source Code</h4><p>The challenge provides the source code of a simple Java program, which simulates the behavior of the vault door. Here’s what the code does:</p><ol><li>The program prompts the user to input a password in the format picoCTF{&lt;password&gt;}.</li><li>It then extracts the actual password from the input by removing the picoCTF{prefix and the closing }.</li><li>The extracted password is passed to the checkPassword function, which compares it to a hardcoded correct password.</li></ol><p>The key to solving the challenge is to understand how the password verification works. The correct password is explicitly provided within the checkPassword function in the source code.</p><pre>import java.util.*;<br><br>class VaultDoorTraining {<br>    public static void main(String args[]) {<br>        VaultDoorTraining vaultDoor = new VaultDoorTraining();<br>        Scanner scanner = new Scanner(System.in); <br>        System.out.print(&quot;Enter vault password: &quot;);<br>        String userInput = scanner.next();<br> String input = userInput.substring(&quot;picoCTF{&quot;.length(),userInput.length()-1);<br> if (vaultDoor.checkPassword(input)) {<br>     System.out.println(&quot;Access granted.&quot;);<br> } else {<br>     System.out.println(&quot;Access denied!&quot;);<br> }<br>    }<br><br>    public boolean checkPassword(String password) {<br>        return password.equals(&quot;w4rm1ng_Up_w1tH_jAv4_be8d9806f18&quot;);<br>    }<br>}</pre><p>Here’s a breakdown:</p><ul><li><strong>Password Input:</strong> The program expects an input string in the format picoCTF{&lt;password&gt;}.</li><li><strong>Password Extraction:</strong> The actual password to be checked is extracted by removing the first 7 characters (picoCTF{) and the last character (}) from the user input.</li><li><strong>Password Verification:</strong> The extracted password is compared to the hardcoded correct password &quot;w4rm1ng_Up_w1tH_jAv4_be8d9806f1</li></ul><p><strong>Given the password is clearly visible in the source code, the flag is simply the concatenation of picoCTF{ with the extracted password.</strong></p><p>Therefore the flag is:</p><p>picoCTF{w4rm1ng_Up_w1tH_jAv4_be8d9806f18}</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=293eee761b57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Engineering 101 : Transformation]]></title>
            <link>https://medium.com/@krizzsrivastava/reverse-engineering-101-transformation-04de05821bb9?source=rss-30c8ba8983ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/04de05821bb9</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[picoctf]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[binary-encoding]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Krish Srivastava]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 14:21:29 GMT</pubDate>
            <atom:updated>2024-08-15T14:21:29.524Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reverse Engineering 101 : Transformation</h3><figure><img alt="Source : https://zdresearch.com/shop/reverse-engineering/" src="https://cdn-images-1.medium.com/max/800/0*5fmaud15DHIvQ441.jpg" /><figcaption>Source : <a href="https://zdresearch.com/shop/reverse-engineering/">https://zdresearch.com/shop/reverse-engineering/</a></figcaption></figure><p>The ‘Transformation’ challenge from picoCTF offers an intriguing glimpse into the world of encoding and decoding. This writeup will walk you through the process of solving this challenge, explaining the concepts and providing the code needed to reveal the hidden flag.</p><h3><strong>Challenge Overview:</strong></h3><ul><li><strong>Name:</strong> Transformation</li><li><strong>Category:</strong> Reverse Engineering</li></ul><p>The challenge presents us with an encoded string and a hint about the encoding process. Our task is to reverse this process and retrieve the original flag.</p><h3><strong>Understanding the Encoding:</strong></h3><p>The challenge provides us with an encoded string and the following Python snippet that was used for encoding:</p><pre>enc = &#39;&#39;.join([chr((ord(flag[i]) &lt;&lt; 8) + ord(flag[i + 1])) for i in range(0, len(flag), 2)])</pre><p><strong>Let’s break down what this code does:</strong></p><ul><li>It iterates through the flag string, taking two characters at a time.</li><li>For each pair of characters, it shifts the ASCII value of the first character left by 8 bits (equivalent to multiplying by 256).</li><li>It adds the ASCII value of the second character to this result.</li><li>It converts this sum back into a character.</li><li>All these characters are joined together to form the encoded string.</li></ul><h3><strong>The Decoding Process:</strong></h3><p>To decode the string, we need to reverse this process. Here’s how we can do it:</p><ol><li>For each character in the encoded string:</li></ol><ul><li>Extract the upper 8 bits (by shifting right 8 bits) to get the first character of the original pair.</li><li>Extract the lower 8 bits to get the second character of the original pair.</li></ul><p>2. Combine all these extracted characters to reconstruct the original flag.</p><h3><strong>Solution:</strong></h3><pre>def decode(enc):<br>    flag = &quot;&quot;<br>    for char in enc:<br>        ascii_val = ord(char)<br>        flag += chr(ascii_val &gt;&gt; 8)<br>        flag += chr(ascii_val &amp; 255)<br>    return flag<br><br>with open(&#39;enc&#39;, &#39;r&#39;, encoding=&#39;utf-8&#39;) as file:<br>    enc = file.read().strip()<br><br>decoded_flag = decode(enc)<br>print(decoded_flag)</pre><p>This would give us the flag.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04de05821bb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retr0DB : Building a Database in Rust]]></title>
            <link>https://medium.com/@krizzsrivastava/retr0db-building-a-database-in-rust-b223e2b98cbd?source=rss-30c8ba8983ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/b223e2b98cbd</guid>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Krish Srivastava]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 09:09:14 GMT</pubDate>
            <atom:updated>2024-07-15T09:09:14.128Z</atom:updated>
            <content:encoded><![CDATA[<h3>Retr0DB : Building a Database in Rust</h3><p>For many software developers and students, understanding the internals of a database system seems daunting. Motivated by this, I tried building a simple database engine from scratch in Rust, inspired by the tutorial series that teaches <a href="https://cstack.github.io/db_tutorial/parts/part1.html">how to build a SQLite clone in C</a>. This project aims to provide insights into the basics of database design and operation while leveraging the safety and concurrency features of Rust.</p><h3>Why Build a Database?</h3><p>Databases are everywhere in software development, serving as the backbone for data storage and retrieval in applications across industries. However, the intricate details of how databases manage, store, and retrieve data efficiently often remain obscured behind layers of abstractions. By building a database from scratch, I hoped to peel back these layers, gaining a deeper understanding of core concepts like SQL parsing, B-trees, transactions, and more.</p><h3>Why Choose Rust?</h3><p>Rust offers memory safety guarantees without a garbage collector, making it ideal for building performance-critical applications that require direct control over memory layout — characteristics crucial for a database engine. Additionally, Rust’s robust concurrency support is beneficial for handling multiple connections and ensuring data consistency across threads, an essential aspect of modern database systems.</p><h3>Overview</h3><p>Retr0DB mimics a very simplified version of SQLite, supporting basic CRUD (Create, Read, Update, Delete) operations through a custom SQL-like language. The project is structured into several components:</p><ul><li><strong>db_core</strong>: Contains the fundamental logic for managing data structures and storing data. It implements simple data manipulation methods and query execution. Here’s a simple example of how a table is defined and how data insertion is handled:</li></ul><pre>pub struct Table {<br>    pub name: String,<br>    pub columns: HashMap&lt;String, DataType&gt;,<br>    pub data: Vec&lt;HashMap&lt;String, String&gt;&gt;,<br>}<br><br>impl Table {<br>    pub fn new(name: String) -&gt; Self {<br>        Table {<br>            name,<br>            columns: HashMap::new(),<br>            data: Vec::new(),<br>        }<br>    }<br><br>    pub fn insert(&amp;mut self, row: HashMap&lt;String, String&gt;) {<br>        self.data.push(row);<br>    }<br>}</pre><ul><li><strong>db_parser</strong>: A simple parser built using LALRPOP to interpret SQL-like commands. It breaks down user input into commands that the core engine can execute. Here’s a simplified version of the LALRPOP grammar for handling a basic CREATE TABLE statement:</li></ul><pre>grammar;<br><br>use crate::sql::{SqlStatement, CreateTableStatement};<br><br>pub SqlStatement: SqlStatement = {<br>    &lt;create_table_stmt&gt; =&gt; SqlStatement::CreateTable(Box::new(create_table_stmt))<br>};<br><br>CreateTableStmt: CreateTableStatement = {<br>    &quot;CREATE&quot; &quot;TABLE&quot; &lt;table_name:Ident&gt; &quot;(&quot; &lt;fields:Comma&lt;FieldSpec&gt;&gt; &quot;)&quot; &quot;;&quot; =&gt; {<br>        CreateTableStatement {<br>            table_name,<br>            fields,<br>        }<br>    }<br>};<br><br>FieldSpec: (String, DataType) = {<br>    &lt;field_name:Ident&gt; &lt;data_type:DataType&gt; =&gt; (field_name, data_type)<br>};<br><br>Ident: String = {<br>    &lt;n:r#&quot;[a-zA-Z_][a-zA-Z0-9_]*&quot;#&gt; =&gt; n.to_string()<br>};<br><br>DataType: DataType = {<br>    &quot;INT&quot; =&gt; DataType::Int,<br>    &quot;TEXT&quot; =&gt; DataType::Text,<br>};</pre><ul><li><strong>db_server</strong>: A TCP server that handles requests from multiple clients simultaneously, relying on Rust’s asynchronous programming capabilities. Here’s a simplified version of the server’s request handling:</li></ul><pre>fn handle_client(mut stream: TcpStream, server: &amp;mut Database) {<br>    let mut buffer = [0; 1024];<br>    stream.read(&amp;mut buffer).unwrap();<br>    let command = String::from_utf8_lossy(&amp;buffer);<br>    let result = server.execute(command.to_string());<br>    stream.write(result.as_bytes()).unwrap();<br>}</pre><ul><li><strong>db_client</strong>: A command-line interface that allows users to interact with the database by sending SQL commands over the network to the server. The client sends SQL commands as plain text over the TCP connection, which the server reads, executes, and sends back the results.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*tAKUlI2lpazToTqHKtSZUQ.png" /><figcaption>Table creation and data insertion</figcaption></figure><p>For a deeper dive into the project’s structure and to view the full source code, visit the <a href="https://github.com/retr0-kernel/Retr0DB">Github</a> repository.</p><h4>Crafting the SQL Parser with LALRPOP</h4><p>One of the more intricate aspects of Retr0DB was developing the SQL parser. The parser’s role is to interpret the SQL-like syntax provided by the user and convert it into a structured format that the database engine can execute. LALRPOP was selected for this task due to its powerful yet user-friendly approach to defining complex grammars, which are commonly needed for parsing programming and markup languages.</p><h4>Designing the Grammar</h4><p>The grammar for Retr0DB’s SQL-like language was crafted to support a simplified subset of SQL operations, such as creating tables, inserting data, and querying data. This involved defining rules and productions in a way that aligns closely with SQL standards but simplified for educational purposes. Here’s a brief overview of the process:</p><ul><li><strong>Identifying Key Components</strong>: The grammar needed to recognize key SQL components like table names, column lists, and value lists. Each component required a clear and precise definition to ensure accurate parsing.</li><li><strong>Handling Different Commands</strong>: Separate grammar rules were defined for different commands (CREATE, SELECT, INSERT) to handle their unique syntaxes and parameters.</li><li><strong>Integrating Rust Types</strong>: One of the strengths of LALRPOP is its seamless integration with Rust’s type system. The grammar definitions directly construct Rust data structures, which are then passed on to the database engine.</li></ul><h3>Conclusion</h3><p>Building Retr0DB was a deeply enlightening journey into the core of database systems and Rust programming. This project not only allowed me to practically apply Rust’s advanced features but also provided me with a hands-on understanding of database operations — from parsing SQL commands using LALRPOP to managing data storage and retrieval.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b223e2b98cbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing SSL/TLS in a Local Development Environment]]></title>
            <link>https://medium.com/@krizzsrivastava/implementing-ssl-tls-in-a-local-development-environment-fc92a1a1e7cd?source=rss-30c8ba8983ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc92a1a1e7cd</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[ssltls]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <dc:creator><![CDATA[Krish Srivastava]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 06:03:50 GMT</pubDate>
            <atom:updated>2024-04-26T06:03:50.569Z</atom:updated>
            <content:encoded><![CDATA[<p>Security is paramount in the development and deployment of web applications. Today, I’ll guide you through setting up an SSL/TLS environment locally, using <strong>OpenSSL</strong> and <strong>Flask</strong>. This is especially useful for developers looking to implement and test secure communication protocols during the development phase.</p><p><strong>Step 1: Creating a Private Key and Certificate Signing Request (CSR)</strong></p><p>First, we need to create a private key and a Certificate Signing Request (CSR). This can be done using <strong>OpenSSL</strong>. This is a foundational step in securing communications between your server and clients.</p><pre>openssl req -newkey rsa:2048 -nodes -keyout &lt;file_name&gt;.key -out &lt;file_name&gt;.csr</pre><p>The command above generates a <strong>2048-bit RSA key pair</strong>. Remember the -nodes flag ensures the private key is not encrypted, which simplifies development without compromising security, as this setup is not intended for production development.</p><p><strong>Step 2: Creating a Self-Signed Certificate</strong></p><p>Next, we create a self-signed certificate using the private key and CSR generated in the first step. Self-signed certificates are great for testing and development because they do not require a certificate authority (CA).</p><pre>openssl x509 -signkey &lt;file-name&gt;.key -in &lt;file-name&gt;.csr -req -days 365 -out &lt;file-name&gt;.crt</pre><p>This certificate will be valid for 365 days. It tells clients that the server they connect to is the same one described in the CSR.</p><p><strong>Step 3: Configuring the Flask Server</strong></p><p>Now, let’s configure a local Flask server to use this SSL/TLS certificate.</p><pre>from flask import Flask<br>app = Flask(__name__)<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(ssl_context=(&#39;path/to/&lt;file-name&gt;.crt&#39;, &#39;path/to/&lt;file-name&gt;.key&#39;))</pre><p>Running this will now create a HTTPS server locally.</p><p>Now if we run this server using,</p><pre>pyhton app.py</pre><p>We should see a security prompt, as this is a self-signed certificate.</p><figure><img alt="Security Prompt" src="https://cdn-images-1.medium.com/max/833/1*qq8zFhVGpfGlFGuqeBKjgg.png" /><figcaption>Security Prompt</figcaption></figure><figure><img alt="Self-signed SSL certificate" src="https://cdn-images-1.medium.com/max/540/1*C5AztvwR0ZXqzCS2YU5qJA.png" /><figcaption>SSL Certificate</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc92a1a1e7cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSRF (Server Side Request Forgery) Attacks]]></title>
            <link>https://medium.com/@krizzsrivastava/ssrf-server-side-request-forgery-attacks-a40f608fcc3a?source=rss-30c8ba8983ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/a40f608fcc3a</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[ssrf]]></category>
            <dc:creator><![CDATA[Krish Srivastava]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 14:21:38 GMT</pubDate>
            <atom:updated>2024-03-26T16:35:49.176Z</atom:updated>
            <content:encoded><![CDATA[<p>Server-side request forgery is a web security vulnerability that allows an attacker to cause the server-side application to make requests to an unintended location.</p><h3>SSRF attacks against the server</h3><p>Attacker causes the application to make an HTTP request back to the server that is hosting the application, via its loopback network interface. This typically involves supplying a URL with a hostname like <strong><em>127.0.0.1</em></strong> (a reserved IP address that points to the loopback adapter) or <strong><em>localhost</em></strong> (a commonly used name for the same adapter).</p><p>For Example :- A shopping store application has a functionality to that a user can check when an item is in stock. When a user views a stock status, their browser will make the following request,</p><pre>POST /product/stock HTTP/1.0 <br>Content-Type: application/x-www-form-urlencoded <br>Content-Length: 118<br>stockApi=http://stock.weliketoshop.net:8080/product/stock/check%3FproductId%3D6%26storeId%3D1</pre><p>This causes the server to make a request to the specified URL, retrieve the status and return it back. An attacker can exploit this by simply modifying the URL local to the server like,</p><pre>POST /product/stock HTTP/1.0 <br>Content-Type: application/x-www-form-urlencoded <br>Content-Length: 118<br>stockApi=http://localhost/admin</pre><p>Here in the above request, the server would fetch the contents of the <strong><em>/admin</em> </strong>URL. Although an attacker can visit the URL but cannot see anything of interest as it may be authenticated. However, if the request to the <strong><em>/admin</em></strong> URL comes from the local machine then it may be exploitable.</p><h3>SSRF attacks against other back-end systems</h3><p>In some cases, the application server is able to interact with backend systems that are not directly reachable by users. These systems often have non-routable private IP addresses. The back-end systems are normally protected by the network topology, so they often have a weaker security posture. In many cases, internal back-end systems contain sensitive functionality that can be accessed without authentication by anyone who is able to interact with the systems.</p><p>For accessing a different administrative interface with a known IP, attacker can modify the request as,</p><pre>POST /product/stock HTTP/1.0 <br>Content-Type: application/x-www-form-urlencoded <br>Content-Length: 118 <br><br>stockApi=http://192.168.0.68/admin</pre><h3>SSRF with blacklist-based input filters</h3><p>Some applications block input containing hostnames like <strong><em>127.0.0.1</em></strong> and <strong><em>localhost</em></strong>, or sensitive URLs like <strong><em>/admin</em></strong>. In this situation, you can often circumvent the filter using the following techniques:</p><ul><li>Use an alternative IP representation of <strong><em>127.0.0.1</em></strong>, such as <strong>2130706433</strong>, <strong><em>017700000001</em></strong>, or <strong><em>127.1</em></strong>.</li><li>Register your own domain name that resolves to <strong><em>127.0.0.1</em></strong>. One can use <strong><em>spoofed.burpcollaborator.net</em></strong> for this purpose.</li><li>Obfuscate blocked strings using URL encoding or case variation.</li><li>Provide a URL that you control, which redirects to the target URL. Try using different redirect codes, as well as different protocols for the target URL. For example, switching from an <strong><em>http:</em></strong> to <strong><em>https:</em></strong> URL during the redirect has been shown to bypass some anti-SSRF filters.</li></ul><h3>SSRF with whitelist-based input filters</h3><p>Some applications only allow inputs as a whitelist of permitted values. The filter may look at the beginning of the input, or contained within it. It can be bypassed by exploiting inconsistencies in URL parsing.</p><ul><li>For embedding credentials in a URL before the hostname we can use <strong><em>@</em></strong> character. For example: <a href="https://expected-host:fakepassword@evil-host`/"><strong><em>https://expected-host:fakepassword@evil-host</em></strong></a></li><li>For passing a given URL before the actual URL (passing an URL fragment) we can use <strong><em>#</em></strong> character. For example: <a href="https://evil-host/#expected-host%60"><strong><em>https://evil-host#expected-host</em></strong></a></li><li>We can also use the DNS naming hierarchy to place a DNS that I control before the accepted input. For example: <a href="https://expected-host.evil-host`/"><strong><em>https://expected-host.evil-host</em></strong></a></li><li>Double encoding can also help pass these filters.</li></ul><h3>Bypassing SSRF filters via open redirection</h3><p>Sometimes it is also possible to exploit using SSRF by exploiting open redirection vulnerabilities. Provided API used to make backend HTTP requests supports redirections. This can be exploited as:</p><pre>/product/nextProduct?currentProductId=6&amp;path=http://evil-user.net</pre><p>above returns a redirection to:</p><pre>http://evil-user.net</pre><p>It would look like this as a request:</p><pre>POST /product/stock HTTP/1.0 <br>Content-Type: application/x-www-form-urlencoded <br>Content-Length: 118 <br><br>stockApi=http://weliketoshop.net/product/nextProduct?currentProductId=6&amp;path=http://192.168.0.68/admin</pre><h3>Blind SSRF vulnerabilities</h3><p>Blind SSRF vulnerabilities arise when an application can be induced to issue a back-end HTTP request to a supplied URL, but the response from the back-end request is not returned in the application’s front-end response.</p><p>Most reliable way of finding Blind SSRF vulnerabilities is using <strong><em>out-of-band (OAST) techniques</em></strong>.</p><h4>WHAT IS OAST SECURITY TESTING?</h4><p>Out-of-band application security testing (OAST) uses external servers to see otherwise invisible vulnerabilities. It was introduced to further improve the DAST (dynamic application security testing) model.</p><h4>How does OAST work?</h4><ol><li><strong>Attacking from outside (conventional):</strong></li></ol><p>When you send a DAST payload and your target comes back to you with a response suggesting a vulnerability, you can be pretty sure it’s real. Dynamic testing has achieved the success it has, because it works well in these situations.</p><blockquote>Now what if the server wont respond to your requests? In that case we use OAST techniques.</blockquote><p>2. Seeing over the horizon:</p><p>Burp Collaborator can search for a huge range of vulnerabilities that were once invisible to DAST testing.</p><p>If a vulnerability is blind, then it sends back no useful response to us when we send a test attack — even if that attack is successful. We need a way to bypass this. Out-of-band testing methods are that bypass. It is done by sending an attack payload that causes an interaction with an external system we have control over, that sits outside the target domain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a40f608fcc3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>