<?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 Thushakaran Balasubramaniyam on Medium]]></title>
        <description><![CDATA[Stories by Thushakaran Balasubramaniyam on Medium]]></description>
        <link>https://medium.com/@tthushakaran19?source=rss-de037e479219------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6BTtjGp3SIM9uT8Xgd_h5w.png</url>
            <title>Stories by Thushakaran Balasubramaniyam on Medium</title>
            <link>https://medium.com/@tthushakaran19?source=rss-de037e479219------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:17:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tthushakaran19/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[Fingerprints of Data: Secure Digest Functions, HMAC, and the Integrity of Distributed Systems]]></title>
            <link>https://medium.com/@tthushakaran19/fingerprints-of-data-secure-digest-functions-hmac-and-the-integrity-of-distributed-systems-45e26f52f4c4?source=rss-de037e479219------2</link>
            <guid isPermaLink="false">https://medium.com/p/45e26f52f4c4</guid>
            <dc:creator><![CDATA[Thushakaran Balasubramaniyam]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 08:07:32 GMT</pubDate>
            <atom:updated>2026-07-10T08:07:32.756Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How MD5, SHA-1, SHA-256, and HMAC answer the fundamental question: has this data been tampered with?</em></h4><p>Encryption protects data from being read by the wrong people. But encryption alone doesn’t tell you whether the data has been modified. A message could be encrypted, intercepted, and replaced with a different encrypted message — and the recipient would have no way to detect the substitution.</p><p>This is where cryptographic hash functions enter the picture. They are the integrity guarantors of distributed systems — the mechanism by which systems verify that code hasn’t been corrupted, certificates haven’t been forged, and messages haven’t been altered in transit.</p><p>In this final article in the series, we explore how digest functions work, trace the evolution from MD5 through SHA-256, introduce HMAC as an authenticated version of hashing, and survey how these algorithms underpin digital signatures, TLS certificates, Git, blockchain, and more.</p><h3>What Is a Cryptographic Hash Function?</h3><p>A cryptographic hash function takes an input of arbitrary length and produces a fixed-length output called a digest (or hash). The function is deterministic — the same input always produces the same output — and has these essential security properties</p><p>• Preimage resistance — Given a hash output H, it is computationally infeasible to find any input M such that hash(M) = H.</p><p>• Second preimage resistance — Given an input M1 and its hash H, it is computationally infeasible to find a different input M2 (M2 ≠ M1) such that hash(M2) = H.</p><p>• Collision resistance — It is computationally infeasible to find any two distinct inputs M1 and M2 such that hash(M1) = hash(M2).</p><p>• Avalanche effect — A small change in the input (even a single bit) produces a completely different output.</p><p>These properties, combined, make hash functions ideal for verifying integrity: if even one byte of a file changes, its hash changes completely and unpredictably.</p><pre>SHA-256(&quot;Hello, World!&quot;)<br>= dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986d<br>SHA-256(&quot;Hello, World.&quot;) // period instead of !<br>= 5a0b8855753edd8a1bcf6a4f03f8a40e6c08c55f90e4dde6fad22b50a0f8f0b4</pre><p>Identical structure, completely different outputs. This is the avalanche effect in action.</p><h3>MD5 — Born Fast, Died Broken</h3><h4><strong>Design</strong></h4><p>Message Digest 5 (MD5) was designed by Ron Rivest (the R in RSA) and published in 1991. It produces a 128-bit (16-byte) digest. MD5 processes input in 512-bit blocks through four rounds of 16 operations each, using a combination of bitwise logic, modular addition, and bit rotation.</p><pre>MD5(&#39;password&#39;) = 5f4dcc3b5aa765d61d8327deb882cf99</pre><h4><strong>The Fall of MD5</strong></h4><p>MD5’s collision resistance was broken definitively in 2004 by Xiaoyun Wang and colleagues, who demonstrated that two different inputs could be crafted to produce the same MD5 hash. This is catastrophically dangerous for digital certificates: if an attacker can create a malicious certificate with the same MD5 hash as a legitimate one, a Certificate Authority’s signature on the legitimate certificate would also validate the malicious one.</p><p>In 2008, researchers exploited MD5 collisions to create a rogue Certificate Authority certificate, demonstrating a practical attack against the SSL certificate infrastructure. After this, browsers and CAs deprecated MD5 for certificates.</p><p>Today, MD5 has no legitimate use in security-sensitive contexts. It survives only as a fast checksum for non-security purposes (detecting accidental data corruption in file transfers), where collision attacks are not a concern. For any cryptographic purpose — password hashing, signatures, certificates — MD5 is forbidden.</p><h3>SHA-1 — The Middle Generation</h3><h4><strong>Design and Adoption</strong></h4><p>Secure Hash Algorithm 1 (SHA-1) was designed by the NSA and published by NIST in 1995. It produces a 160-bit (20-byte) digest — 32 bits longer than MD5 — using a Merkle-Damgard construction with 80 rounds. SHA-1 became the backbone of internet security for over a decade, used in TLS, SSH, PGP, and X.509 certificates.</p><pre>SHA-1(&#39;password&#39;) = 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8</pre><h4><strong>SHA-1’s Collision Problems</strong></h4><p>Theoretical weaknesses in SHA-1 were identified as early as 2005, when Wang et al. showed that collisions could be found significantly faster than brute force (2⁸⁰ operations). The attack required 2⁶³ operations — still expensive but alarming.</p><p>In 2017, Google’s Project team published SHAttered — the first real-world SHA-1 collision. They produced two different PDF files with identical SHA-1 hashes. The attack required approximately 9.2 × 10¹⁸ SHA-1 computations — roughly the equivalent of 6,500 years of single-CPU computation, but achievable in practice using GPU clusters.</p><p>This made SHA-1 unsuitable for certificates and code signing. Google Chrome and Mozilla Firefox deprecated SHA-1 certificates in 2017. GitHub disabled SHA-1 as a valid commit signature algorithm. NIST deprecated SHA-1 for digital signatures in 2011 and disallowed its use in digital signatures by 2013, with full deprecation by 2030.</p><p>SHA-1 still sees use in non-collision-sensitive contexts — for example, Git uses SHA-1 to identify commits by content (a transition to SHA-256 is underway). But for any application where an attacker could gain by crafting collisions, SHA-1 is broken.</p><h3>SHA-2 — The Modern Standard</h3><h4><strong>The SHA-2 Family</strong></h4><p>SHA-2 is a family of hash functions designed by the NSA and standardized by NIST in 2001. All SHA-2 variants use a Merkle-Damgard structure with Davies-Meyer compression</p><p>• SHA-224–224-bit digest, truncated variant of SHA-256.</p><p>• SHA-256–256-bit digest, processes 512-bit blocks in 64 rounds. The most widely deployed.</p><p>• SHA-384–384-bit digest, truncated variant of SHA-512.</p><p>• SHA-512–512-bit digest, processes 1024-bit blocks in 80 rounds. Faster than SHA-256 on 64-bit hardware.</p><p>• SHA-512/256 — SHA-512 algorithm, truncated to 256 bits. Fast on 64-bit hardware, avoids SHA-256’s speed disadvantage.</p><h4><strong>SHA-256 in Depth</strong></h4><p>SHA-256 processes input in 512-bit (64-byte) message blocks. Before processing, the message is padded so its length is congruent to 448 mod 512 bits, and the original length is appended as a 64-bit big-endian integer.</p><p>SHA-256 maintains eight 32-bit state words (a, b, c, d, e, f, g, h), initialized from the fractional parts of the square roots of the first eight primes. For each 512-bit block, it performs 64 rounds using</p><p>• A message schedule that expands the 16 32-bit words of the block into 64 32-bit words using rotations and XOR.</p><p>• A compression function using bitwise operations (Ch, Maj), bitwise rotations (Σ0, Σ1), and modular addition.</p><p>• Round constants derived from the fractional parts of the cube roots of the first 64 primes.</p><pre>SHA-256(&#39;&#39;) = e3b0c44298fc1c149afbf4c8996fb924<br>27ae41e4649b934ca495991b7852b855</pre><p>SHA-256 is currently considered secure. No practical collision attacks are known. Its 256-bit output means brute-force collision finding would require 2¹²⁸ operations — computationally infeasible even for state actors.</p><h4><strong>SHA-3 — A Different Approach</strong></h4><p>SHA-3, standardized in 2015, is not a SHA-2 variant — it uses a completely different algorithm called Keccak, based on a sponge construction rather than Merkle-Damgard. It provides equivalent security to SHA-2 but with a different internal structure, providing algorithm diversity in case a weakness in the Merkle-Damgard design is discovered. SHA-3 sees growing adoption but SHA-256 remains dominant in existing infrastructure.</p><h3>HMAC — Authenticated Hashing</h3><h4><strong>The Problem: Hash Functions Are Not MACs</strong></h4><p>A plain cryptographic hash is a public function: anyone can compute SHA-256(M). If Alice sends Bob a file with its SHA-256 hash for integrity checking, Eve can intercept, modify the file, compute a new SHA-256 hash, and Bob would see a valid match. The hash verifies integrity against accidental corruption, but not against malicious tampering.</p><p>To authenticate the source of a message, we need a Message Authentication Code (MAC) — a keyed hash. Only parties who know the key K can produce a valid MAC for message M.</p><h4><strong>HMAC Construction</strong></h4><p>HMAC (Hash-based MAC), defined in RFC 2104 (1997) and FIPS 198, provides a standardized way to turn any cryptographic hash function into a MAC</p><pre>HMAC(K, M) = H((K ⊕ opad) || H((K ⊕ ipad) || M))<br>Where:<br>H = underlying hash function (e.g., SHA-256)<br>K = secret key (padded to block size)<br>opad = 0x5c repeated to block length<br>ipad = 0x36 repeated to block length<br>|| = concatenation<br>⊕ = XOR</pre><p>The double-hashing construction with ipad/opad was carefully designed to prevent length-extension attacks — a vulnerability in naive constructions like H(K || M). HMAC-SHA-256 is the most widely used MAC in practice.</p><h4><strong>Why HMAC Resists Length-Extension Attacks</strong></h4><p>Merkle-Damgard hash functions (MD5, SHA-1, SHA-256) are vulnerable to a length-extension attack: if you know H(M), you can compute H(M || padding || M’) for arbitrary M’ without knowing M. A naive MAC construction of H(K || M) would be vulnerable to this.</p><p>HMAC’s nested structure prevents this: the inner hash H(ipad || M) is computed first, then the outer hash H(opad || inner) is applied. An attacker who knows HMAC(K, M) cannot extend M without knowing K. SHA-3 (Keccak) is naturally immune to length extension due to its sponge construction.</p><h3>Hash Functions in Digital Signatures</h3><p>Digital signatures don’t directly sign a message — they sign the message’s hash. This is essential for two reasons: asymmetric operations on large messages are computationally prohibitive, and signing a hash provides a fixed-size, predictable input to the signature algorithm.</p><pre>Sign: S = RSA_sign(private_key, SHA-256(M))<br>Verify: SHA-256(M) == RSA_verify(public_key, S)</pre><p>The collision resistance of the hash function is critical here. If an attacker can find M1 ≠ M2 with SHA-256(M1) = SHA-256(M2), they can get a legitimate party to sign M1 (e.g., a benign document) and then present the same signature as valid for M2 (e.g., a malicious contract). This is exactly the attack that broke MD5 certificates.</p><p>SHA-256 is the current standard for signatures in X.509 certificates (SHA-256WithRSAEncryption, ecdsa-with-SHA256), code signing (Windows Authenticode, Apple notarization, APK signing), and SSH host key verification.</p><h3>Hash Functions in TLS Certificates</h3><p>An X.509 certificate contains the server’s public key plus identity information (domain name, organization, validity period). A Certificate Authority (CA) signs the certificate’s hash with its private key. When your browser connects to a server, it</p><p>• Downloads the server’s certificate.</p><p>• Computes SHA-256 of the certificate’s TBSCertificate field.</p><p>• Verifies the CA’s RSA or ECDSA signature against this hash using the CA’s public key.</p><p>• Checks that the CA’s public key is in the browser’s trusted root store.</p><p>If the hash matches, the certificate is genuine — no one has tampered with the public key or domain name it contains. The chain of trust flows from the server certificate to an intermediate CA to a root CA, with each link verified by SHA-256.</p><p>The migration from SHA-1 to SHA-256 in certificates (completed industry-wide around 2017) is one of the most important cryptographic transitions in internet history, driven directly by the SHA-1 collision attack.</p><h3>Other Uses of Secure Digest Functions in Distributed Systems</h3><h4><strong>Password Storage</strong></h4><p>Passwords should never be stored as plaintext or as simple hashes. SHA-256(password) is fast to compute, which allows brute-force attacks: an attacker with a stolen hash database can try billions of password guesses per second using a GPU.</p><p>Password storage instead uses slow, memory-hard functions: bcrypt (1999), scrypt (2009), and Argon2 (2015, PHC winner). These are not general-purpose hash functions — they are specifically designed to be slow and memory-intensive, making brute force impractical. Argon2id is the current recommendation.</p><h4><strong>Git Content Addressing</strong></h4><p>Git identifies every object (blob, tree, commit, tag) by the SHA-1 hash of its contents. A commit’s SHA-1 covers the tree it points to, the parent commits, the author, the message, and the timestamp. This creates a tamper-evident history: changing any commit changes its hash and the hash of all commits that follow. Git is currently migrating to SHA-256 for new repositories.</p><h4><strong>Blockchain</strong></h4><p>Bitcoin and most blockchain systems use SHA-256 as the core integrity mechanism. Each block header includes the SHA-256 hash of the previous block, creating a chain. Mining (proof of work) requires finding a nonce such that SHA-256(SHA-256(block_header)) produces a hash below a target threshold. This double-SHA-256 construction was chosen to counter the length-extension vulnerability in Merkle-Damgard.</p><h4><strong>Merkle Trees</strong></h4><p>Distributed systems use Merkle trees — binary trees where each leaf node contains the hash of a data block and each parent node contains the hash of its children’s hashes — to efficiently verify large datasets. A Merkle tree over n blocks allows verifying any individual block with only O(log n) hash comparisons. Used in: Bitcoin transactions, Certificate Transparency logs, distributed databases like Cassandra for anti-entropy, IPFS content addressing, and TLS Certificate Transparency.</p><h4><strong>Key Derivation</strong></h4><p>HKDF (HMAC-based Key Derivation Function, RFC 5869) uses HMAC-SHA-256 to derive multiple cryptographic keys from a single source of entropy. TLS 1.3 uses HKDF extensively: the shared secret from ECDHE is fed into HKDF to produce the handshake traffic keys, master secret, application traffic keys, and resumption keys — all derived in a structured, provably secure way.</p><pre>HKDF-Extract: PRK = HMAC-SHA-256(salt, IKM)<br>HKDF-Expand: OKM = HMAC-SHA-256(PRK, info || counter)</pre><h3>Algorithm Selection Guide</h3><p>For new systems in 2024 and beyond, the choices are clear</p><p>• General-purpose hashing (integrity, content addressing): SHA-256 or SHA-3–256.</p><p>• Message Authentication: HMAC-SHA-256.</p><p>• Digital signatures: SHA-256 paired with RSA-PSS or ECDSA (P-256 or Ed25519).</p><p>• Password storage: Argon2id (first choice), bcrypt or scrypt (widely supported alternatives).</p><p>• TLS and certificates: SHA-256 (already the default; migration to SHA-384 for higher-security contexts).</p><p>• Legacy interoperability only: SHA-1 (never for new signatures or certificates).</p><p>• Avoid: MD5 for any cryptographic purpose.</p><h3>Conclusion: The Complete Picture</h3><p>Across this three-part series, we have traced the three families of algorithms that secure distributed systems</p><p>• Symmetric algorithms (AES, ChaCha20) — Fast bulk encryption. The workhorse of data confidentiality.</p><p>• Asymmetric algorithms (RSA, ECDHE, ECDSA) — Solve the key exchange problem, authenticate parties, enable digital signatures.</p><p>• Hash functions and HMAC (SHA-256, HMAC-SHA-256) — Verify integrity, enable signatures, create tamper-evident chains.</p><p>No single algorithm family is sufficient alone. In TLS 1.3, all three work together: ECDHE derives session keys, ECDSA over SHA-256 authenticates the server’s certificate, and AES-256-GCM or ChaCha20-Poly1305 encrypts the data. Each algorithm does what it does best.</p><p>Understanding these algorithms — how they work, why older ones failed, and what makes modern ones secure — is not merely academic. It is the foundation on which every distributed system’s security architecture is built. Every API endpoint, every token, every certificate, every password, every commit hash relies on these mathematical primitives working correctly.</p><p>The next time you see the padlock icon in your browser, you’ll know exactly what’s running underneath.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45e26f52f4c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Secret Keepers: How Symmetric Encryption Powers Distributed Systems]]></title>
            <link>https://medium.com/@tthushakaran19/the-secret-keepers-how-symmetric-encryption-powers-distributed-systems-d969ad31074e?source=rss-de037e479219------2</link>
            <guid isPermaLink="false">https://medium.com/p/d969ad31074e</guid>
            <dc:creator><![CDATA[Thushakaran Balasubramaniyam]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 08:06:47 GMT</pubDate>
            <atom:updated>2026-07-10T08:06:47.443Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>AES, DES, 3DES, and ChaCha20 — the algorithms that encrypt the world’s data, and the key exchange problem they can’t solve alone.</em></h4><p>Every time you open a banking app, stream a video, or send a message, symmetric encryption is working silently in the background. It’s the fastest class of cryptographic algorithm we have — and understanding it is essential for anyone building distributed systems.</p><p>In this article, we’ll explore how secret-key (symmetric) algorithms work, trace their evolution from DES through AES to ChaCha20, and confront the fundamental problem that symmetric encryption cannot solve on its own: how do two parties share a secret key over an untrusted network?</p><h3>What Is Symmetric (Secret-Key) Encryption?</h3><p>Symmetric encryption uses the same key to both encrypt and decrypt data. The sender and receiver must both possess an identical secret key. If Alice wants to send Bob an encrypted message, they both need to know the key K before the conversation begins.</p><pre>Encrypt:  Ciphertext = E(K, Plaintext)<br>Decrypt:  Plaintext  = D(K, Ciphertext)</pre><p>This contrasts with asymmetric (public-key) encryption, where different keys are used for encryption and decryption. Symmetric algorithms are dramatically faster than their asymmetric counterparts — often 100–1000x — making them the workhorse of bulk data encryption in real protocols like TLS, IPsec, and SSH.</p><h3>DES — The Algorithm That Started It All</h3><h4><strong>Origins and Design</strong></h4><p>The Data Encryption Standard (DES) was published by NIST in 1977, based on IBM’s Lucifer cipher and hardened with input from the NSA. It became the world’s first widely adopted commercial encryption standard.</p><p>DES operates on 64-bit blocks of data using a 56-bit key. It uses a Feistel network structure — a technique where the plaintext block is split in half and each half is encrypted in alternating rounds, referencing the other half. DES performs 16 such rounds.</p><pre>Block size : 64 bits<br>Key length : 56 bits (plus 8 parity bits, total 64 bits stored)<br>Structure  : 16-round Feistel network</pre><h4><strong>Why DES Died</strong></h4><p>By the late 1990s, DES’s 56-bit key was its undoing. In 1998, the Electronic Frontier Foundation built a machine called Deep Crack for under $250,000 that broke a DES key in 22 hours by brute force. The key space of 2⁵⁶ — about 72 quadrillion possible keys — had become exhaustively searchable with commodity hardware.</p><p>DES was formally withdrawn as a US federal standard in 2005. Yet its legacy endures: it taught the world what a block cipher should look like, and its successor algorithms build directly on its foundations.</p><h3>3DES — A Temporary Bridge</h3><p>Triple DES (3DES or TDEA) was a stopgap that extended DES’s life by applying the algorithm three times in sequence. Using two or three independent 56-bit keys, it effectively produces key lengths of 112 or 168 bits.</p><pre>Encrypt: C = E(K3, D(K2, E(K1, P)))<br>Decrypt: P = D(K1, E(K2, D(K3, C)))</pre><p>The middle step uses decryption (D) rather than encryption — this is intentional. It ensures backward compatibility: if K1 = K2 = K3, the result is equivalent to single DES.</p><p>3DES was widely used in banking (ATM PIN encryption still often uses it) and payment systems. However, its performance is poor — it’s three DES operations per block — and it inherits DES’s 64-bit block size, making it vulnerable to <em>birthday attacks</em> when processing large volumes of data. NIST deprecated 3DES in 2017 and disallowed it for new systems by 2023.</p><h3>AES — The Modern Standard</h3><h4><strong>The Competition That Changed Everything</strong></h4><p>In 1997, NIST launched an open international competition to replace DES. 15 candidate algorithms from around the world were submitted. After five years of public cryptanalysis and performance evaluation, the Rijndael algorithm — designed by Belgian cryptographers Joan Daemen and Vincent Rijmen — was selected and standardized as AES in 2001.</p><h4><strong>How AES Works</strong></h4><p>AES is a substitution-permutation network (SPN), not a Feistel cipher. It operates on a 4×4 matrix of bytes called the state, transforming it through multiple rounds of four operations</p><p>• SubBytes — Each byte is replaced using a non-linear substitution table (S-box), providing confusion.</p><p>• ShiftRows — Rows of the state matrix are cyclically shifted, spreading data across columns.</p><p>• MixColumns — Each column is multiplied by a fixed matrix over GF(2⁸), providing diffusion.</p><p>• AddRoundKey — The state is XOR’d with the round key derived from the main key.</p><pre>Key sizes  : 128, 192, or 256 bits<br>Block size : 128 bits (fixed)<br>Rounds     : 10 (128-bit), 12 (192-bit), 14 (256-bit)</pre><h4><strong>AES Modes of Operation</strong></h4><p>AES itself is a block cipher — it encrypts exactly 128 bits at a time. Real-world data is longer, so a mode of operation defines how blocks are chained together</p><p>• ECB (Electronic Codebook) — Each block encrypted independently. Never use this; identical plaintext blocks produce identical ciphertext.</p><p>• CBC (Cipher Block Chaining) — Each plaintext block is XOR’d with the previous ciphertext block before encryption. Requires an Initialization Vector (IV).</p><p>• CTR (Counter Mode) — Turns AES into a stream cipher by encrypting sequential counter values. Enables parallel encryption.</p><p>• GCM (Galois/Counter Mode) — CTR mode plus a Galois field authentication tag. Provides both confidentiality and integrity (AEAD). Used in TLS 1.3.</p><p>AES-256-GCM is the gold standard for symmetric encryption in modern distributed systems. It is used in TLS 1.3, Signal Protocol, AWS encryption at rest, and countless other production systems.</p><h3>ChaCha20 — The Challenger</h3><p>ChaCha20 is a stream cipher designed by Daniel J. Bernstein in 2008 as an improvement on his earlier Salsa20 cipher. Unlike AES, which operates on a matrix, ChaCha20 operates on a 512-bit state represented as 16 32-bit words and transforms it through 20 rounds of quarter-round operations.</p><pre>State size : 512 bits (16 x 32-bit words)<br>Key size   : 256 bits<br>Nonce      : 96 bits<br>Counter    : 32 bits</pre><p>ChaCha20 is almost always paired with Poly1305, a message authentication code (MAC), forming the ChaCha20-Poly1305 AEAD construction — analogous to AES-GCM.</p><h4><strong>Why ChaCha20 Matters in Distributed Systems</strong></h4><p>ChaCha20’s key advantage over AES is performance on hardware without AES acceleration instructions. Modern Intel and ARM processors have AES-NI hardware instructions that make AES blazingly fast. But low-power IoT devices, older Android phones, and embedded systems often lack these instructions — and on such hardware, ChaCha20 is 3x faster than AES-CBC.</p><p>Google championed ChaCha20-Poly1305 for HTTPS on mobile devices. Today, TLS 1.3 mandates support for both AES-256-GCM and ChaCha20-Poly1305. When a client lacks AES hardware acceleration, the TLS negotiation favors ChaCha20.</p><p>ChaCha20 is also immune to timing side-channel attacks that can affect AES implementations that use lookup tables, because it relies only on ARX operations (Add, Rotate, XOR) which execute in constant time.</p><h3>The Key Exchange Problem</h3><p>Here is the fundamental crisis that symmetric encryption cannot solve on its own: if Alice and Bob have never met, how do they securely share the secret key?</p><p>Suppose Alice wants to encrypt a file for Bob using AES-256. She needs Bob to have the key. But if she sends the key over the internet, an eavesdropper (Eve) intercepts it, and all subsequent communication is compromised. She can’t encrypt the key with AES — that would require another key, which has the same problem. She could mail it on a USB drive, but that doesn’t scale.</p><p>This is the key distribution problem, and it is not a minor inconvenience. It is the central unsolved problem of symmetric cryptography for open networks.</p><h4><strong>Solutions</strong></h4><p>• Key Distribution Centers (KDC) — A trusted third party holds master keys for all users and issues session keys. Used in Kerberos (the authentication protocol behind Windows Active Directory). Requires trusting the KDC completely.</p><p>• Diffie-Hellman Key Exchange — A mathematical protocol allowing two parties to derive a shared secret over an insecure channel without transmitting the secret itself. This is the elegant solution, and it is the subject of Part 2 of this series.</p><p>• Public Key Infrastructure (PKI) — Uses asymmetric cryptography to encrypt the symmetric key. The symmetric key is then used for bulk data. This hybrid approach is how TLS works.</p><p>In practice, the modern answer is: use asymmetric cryptography to solve the key exchange problem, then use symmetric cryptography for everything else. AES-256-GCM and ChaCha20-Poly1305 encrypt the data; RSA or Elliptic Curve Diffie-Hellman distributes the keys. The two families of algorithms are complementary, not competing.</p><h3>Practical Relevance: Where These Algorithms Live</h3><p>• TLS 1.3 — Uses AES-256-GCM or ChaCha20-Poly1305 for record encryption after the handshake.</p><p>• Signal Protocol — Uses AES-256-CBC for message encryption (with HKDF for key derivation).</p><p>• Full-disk encryption — Windows BitLocker and macOS FileVault use AES-XTS-256.</p><p>• AWS S3 Server-Side Encryption — Uses AES-256 for at-rest encryption.</p><p>• WireGuard VPN — Uses ChaCha20-Poly1305 exclusively, citing its performance and implementation simplicity.</p><p>• LUKS (Linux disk encryption) — Supports AES-XTS as default cipher.</p><p>•<strong> </strong>ATM PIN Block Encryption — Legacy banking infrastructure still uses 3DES, though migration to AES is underway.</p><h3>Comparison at a Glance</h3><p>DES (1977): 56-bit key, 64-bit block, Feistel network. Broken by brute force. Historical interest only.</p><p>3DES (1999): 112/168-bit effective key, 64-bit block. Slow, deprecated. Used in legacy banking.</p><p>AES (2001): 128/192/256-bit key, 128-bit block, SPN structure. The global standard. Fast with hardware support.</p><p>ChaCha20 (2008): 256-bit key, stream cipher. Excellent without AES-NI. Constant-time, side-channel resistant.</p><h3><strong>Conclusion</strong></h3><p>Symmetric encryption is the engine of secure communication. DES established the paradigm; 3DES bought time; AES became the world standard; ChaCha20 extended security to hardware that couldn’t do AES efficiently. Each algorithm reflects the hardware capabilities and threat models of its era.</p><p>But the key exchange problem reminds us that no symmetric algorithm, however mathematically strong, can operate in isolation. In the next article in this series, we explore the asymmetric algorithms — RSA, ElGamal, and Diffie-Hellman — that solved the key distribution problem and made secure communication over open networks possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d969ad31074e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Experimenting with RabbitMQ Work Queues: What I Learned by Breaking Things]]></title>
            <link>https://medium.com/@tthushakaran19/experimenting-with-rabbitmq-work-queues-what-i-learned-by-breaking-things-fed14bd48005?source=rss-de037e479219------2</link>
            <guid isPermaLink="false">https://medium.com/p/fed14bd48005</guid>
            <dc:creator><![CDATA[Thushakaran Balasubramaniyam]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 09:45:18 GMT</pubDate>
            <atom:updated>2026-07-07T09:45:18.447Z</atom:updated>
            <content:encoded><![CDATA[<p>Message queues are one of those distributed systems concepts that sound elegant in a textbook but reveal their true character only when you run them and watch what happens when things go wrong. This post documents my hands-on experiment with the RabbitMQ Work Queue tutorial, the observations I recorded, and the failure scenarios I deliberately triggered to understand the system’s guarantees.</p><h3>Why Message Queues?</h3><p>Before diving into code, it is worth grounding the experiment in theory. Message queues are a <strong>point-to-point</strong> style of indirect communication that achieves two important properties</p><ul><li><strong>Space uncoupling</strong> — the producer does not need to know the identity of the consumer. It just drops a message into the queue and moves on.</li><li><strong>Time uncoupling</strong> — the producer and consumer do not need to be running at the same time. Messages persist in the queue until a consumer picks them up.</li></ul><p>This is fundamentally different from synchronous RPC, where the caller blocks until the remote function returns. With a message queue, the producer fires and forgets; the consumer processes at its own pace.</p><h3>Setting Up the Experiment</h3><p>I implemented the tutorial in <strong>Python</strong> using the pika library, which is the official RabbitMQ client for Python.</p><pre>pip install pika</pre><p>I ran RabbitMQ locally via Docker</p><pre>docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management</pre><p>The management UI at http://localhost:15672 (guest/guest) was invaluable for watching queue depth in real time.</p><h3>The Producer / Queue / Consumer Pattern</h3><p>The core of the Work Queue tutorial is straightforward: one <strong>producer</strong> (called new_task.py) sends messages to a queue, and one or more <strong>workers</strong> (called worker.py) pull from that queue and process each message.</p><p><strong>Producer (</strong><strong>new_task.py)</strong></p><pre>import pika<br>import sys<br><br>connection = pika.BlockingConnection(pika.ConnectionParameters(&#39;localhost&#39;))<br>channel = connection.channel()<br><br>channel.queue_declare(queue=&#39;task_queue&#39;, durable=True)<br><br>message = &#39; &#39;.join(sys.argv[1:]) or &quot;Hello World!&quot;<br>channel.basic_publish(<br>    exchange=&#39;&#39;,<br>    routing_key=&#39;task_queue&#39;,<br>    body=message,<br>    properties=pika.BasicProperties(<br>        delivery_mode=pika.DeliveryMode.Persistent  # make message durable<br>    )<br>)<br>print(f&quot; [x] Sent &#39;{message}&#39;&quot;)<br>connection.close()</pre><p>Worker (worker.py)</p><pre>import pika<br>import time<br><br>connection = pika.BlockingConnection(pika.ConnectionParameters(&#39;localhost&#39;))<br>channel = connection.channel()<br><br>channel.queue_declare(queue=&#39;task_queue&#39;, durable=True)<br><br>def callback(ch, method, properties, body):<br>    print(f&quot; [x] Received {body.decode()}&quot;)<br>    time.sleep(body.count(b&#39;.&#39;))   # each dot = 1 second of simulated work<br>    print(&quot; [x] Done&quot;)<br>    ch.basic_ack(delivery_tag=method.delivery_tag)<br><br>channel.basic_qos(prefetch_count=1)<br>channel.basic_consume(queue=&#39;task_queue&#39;, on_message_callback=callback)<br><br>print(&#39; [*] Waiting for messages. To exit press CTRL+C&#39;)<br>channel.start_consuming()</pre><p>The dots in the message body simulate varying workloads — a message like &quot;heavy task....&quot; simulates 4 seconds of work.</p><h3>Durable vs Transient Queues</h3><p>By default, a RabbitMQ queue disappears when the broker restarts. For production use, you want a <strong>durable</strong> queue that survives restarts.</p><pre>channel.queue_declare(queue=&#39;task_queue&#39;, durable=True)</pre><p><strong>Durable queue</strong> — the queue definition is persisted to disk. If RabbitMQ restarts, the queue reappears.</p><p><strong>Transient queue</strong> — lives only in memory. Fast and low overhead, but all messages are lost on restart.</p><p>Durability has two parts: the <strong>queue</strong> must be declared durable, <em>and</em> each <strong>message</strong> must be published with delivery_mode=Persistent. Either alone is insufficient. I tested this by declaring the queue as durable but forgetting the delivery_mode flag, restarting RabbitMQ, and watching the queue reappear — but empty. The messages were gone.</p><p><strong>Observation:</strong> Durable + persistent message delivery adds latency because RabbitMQ must fsync each message to disk before acknowledging the publish. In my tests, publishing 1000 messages to a durable queue took approximately <strong>2.3 seconds</strong> vs <strong>0.4 seconds</strong> for a transient queue. This is a real trade-off: reliability vs throughput.</p><h3>Message Acknowledgement: What Happens When a Worker Crashes?</h3><p>This is the most important safety feature in the Work Queue model. By default (if you use auto_ack=True), RabbitMQ considers a message delivered the moment it is sent to the consumer — regardless of whether the consumer actually finished processing it. If the worker crashes mid-task, the message is lost forever.</p><p><strong>The safer pattern is manual acknowledgement</strong></p><pre>channel.basic_consume(<br>    queue=&#39;task_queue&#39;,<br>    on_message_callback=callback,<br>    auto_ack=False   # we will ack manually<br>)<br><br># Inside callback, after successful processing:<br>ch.basic_ack(delivery_tag=method.delivery_tag)</pre><p>With manual ack, RabbitMQ keeps the message in an <em>unacknowledged</em> state until the worker sends basic_ack. If the worker&#39;s connection drops before the ack arrives, RabbitMQ requeues the message automatically and delivers it to another available worker.</p><h3><strong>Failure Scenario 1: Killing a Worker Mid-Task</strong></h3><p>I sent a slow task &quot;processing..........&quot; (10 seconds of work) to the queue with two workers running. Worker 1 picked it up. After 3 seconds, I killed Worker 1 with CTRL+C.</p><p><strong>Result:</strong> Worker 2 immediately received the message from the beginning and completed it. No message was lost. The management UI showed the message briefly in “Unacked”, then return to “Ready” before being picked up by Worker 2.</p><p>This is the requeue-on-failure guarantee — and it only works because we used basic_ack correctly.</p><h3>What basic_nack and Requeue Look Like</h3><p>If processing fails for a recoverable reason (e.g., a temporary database unavailability), you can reject and requeue</p><pre>ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)</pre><p><strong>Warning:</strong> If the failure is permanent (e.g., malformed message), always requeue with False or send to a Dead Letter Queue — otherwise you create an infinite loop of the same broken message being redelivered forever.</p><h3>Round-Robin vs Fair Dispatch</h3><h4>Round-Robin (Default)</h4><p>By default, RabbitMQ distributes messages to workers in a simple round-robin fashion — Worker 1 gets message 1, Worker 2 gets message 2, Worker 1 gets message 3, and so on — regardless of workload.</p><p><strong>The problem:</strong> if odd-numbered messages are always heavy (&quot;task..........&quot;) and even-numbered messages are light (&quot;task.&quot;), Worker 1 is perpetually overloaded while Worker 2 idles most of the time.</p><p>I simulated this by sending alternating heavy and light tasks</p><pre>Time 0s  → Worker1: heavy task (10s), Worker2: light task (1s)<br>Time 1s  → Worker2 finishes, idles 9 seconds<br>Time 10s → Worker1 finishes, next pair dispatched</pre><p>Worker 2 was idle 90% of the time. The queue throughput was bottlenecked by Worker 1.</p><p><strong>Fair Dispatch with </strong><strong>prefetch_count</strong></p><p>The fix is to tell RabbitMQ not to give a worker more than N unacknowledged messages at a time</p><pre>channel.basic_qos(prefetch_count=1)</pre><p>With prefetch_count=1, RabbitMQ will not send a new message to a worker that already has one unacknowledged message. This means busy workers stop receiving new work until they finish their current task, and idle workers pick up the slack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*Yvddo3hTQzUp0FLbwkYqGQ.png" /></figure><p>Fair dispatch nearly halved total processing time in this unbalanced workload scenario.</p><p><strong>Observation:</strong> prefetch_count=1 is not always the right value. If tasks are short and lightweight, a prefetch of 1 means constant round-trips to the broker for new messages — high overhead. A prefetch of 10–50 can improve throughput for fast tasks by keeping the consumer&#39;s pipeline full.</p><h3>Failure Scenario 2: RabbitMQ Broker Restart</h3><p>I published 500 persistent messages to the durable queue, then immediately stopped the RabbitMQ container before any worker consumed them.</p><pre>docker stop rabbitmq<br>docker start rabbitmq</pre><p><strong>Result:</strong> All 500 messages were still in the queue after restart. Workers connected and processed them normally.</p><p><strong>Caveat:</strong> RabbitMQ’s persistence is not a hard fsync guarantee by default — there is a short write-buffer window where an unexpected power loss (not a clean stop) could lose the most recent messages. For absolute durability guarantees, use <a href="https://www.rabbitmq.com/confirms.html">publisher confirms</a>.</p><h3>Failure Scenario 3: Consumer Forgets to Ack</h3><p>I modified the worker to never send basic_ack</p><pre>def callback(ch, method, properties, body):<br>    print(f&quot; [x] Received {body.decode()}&quot;)<br>    # ack intentionally omitted</pre><p>After sending 10 messages, the management UI showed all 10 messages in the “Unacked” state — held by the worker but not confirmed. When I restarted the worker, all 10 messages were requeued and delivered again. This showed exactly what happens in a slow memory leak scenario: messages pile up as “Unacked”, consuming RAM in the broker, until the connection drops.</p><p><strong>Lesson:</strong> Always ack, nack, or reject. A missing ack is a resource leak.</p><h3>When to Use Message Queues vs Synchronous RPC</h3><p>This is a design question worth getting right.</p><p><strong>Use a message queue when:</strong></p><ul><li>The producer does not need an immediate result from the consumer.</li><li>Tasks take variable, potentially long amounts of time (image processing, sending emails, generating reports).</li><li>You want to decouple services so that a slow or crashed consumer does not block the producer.</li><li>You need load levelling — absorbing traffic spikes into a queue rather than overwhelming downstream services.</li><li>You require retries and guaranteed delivery.</li></ul><p><strong>Use synchronous RPC when:</strong></p><ul><li>The caller needs the result before it can continue (e.g., looking up an account balance before authorising a payment).</li><li>Latency is critical and adding queue overhead is unacceptable.</li><li>The operation is inherently transactional and must either fully complete or fully fail in one round trip.</li><li>The request-reply pattern maps naturally to the task (e.g., a database query, a calculation service).</li></ul><p>A useful rule of thumb: if you can answer “does the caller need to wait for the result?”, the answer tells you which model to use. Waiting → RPC. Not waiting → queue.</p><h3>Summary of Key Concepts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*2_mQt7gzh5Fjvmv5N-suww.png" /></figure><h3>Final Thoughts</h3><p>The RabbitMQ Work Queue tutorial is deceptively simple in its happy path. What makes it educational is deliberately triggering failures — killing workers, forgetting acks, restarting the broker — and watching how the system responds. The key insight I took away is that <strong>message acknowledgement is the backbone of reliability</strong>. Everything else — durability, fair dispatch, prefetch — layers on top of that foundation.</p><p>For a distributed system student, this experiment makes the theoretical properties of time and space uncoupling very concrete. When you kill Worker 1 and watch Worker 2 seamlessly pick up the task, you have seen time uncoupling working in practice, not just read about it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fed14bd48005" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[External Data Representation and Marshalling in Distributed Systems]]></title>
            <link>https://medium.com/@tthushakaran19/external-data-representation-and-marshalling-in-distributed-systems-e5273e6db472?source=rss-de037e479219------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5273e6db472</guid>
            <dc:creator><![CDATA[Thushakaran Balasubramaniyam]]></dc:creator>
            <pubDate>Sat, 16 May 2026 04:19:13 GMT</pubDate>
            <atom:updated>2026-05-25T07:08:44.536Z</atom:updated>
            <content:encoded><![CDATA[<p>When you write a Java program on your laptop and call a method, you never think about how the data “moves” — it just does. But in a distributed system, where two processes might be running on completely different machines, possibly written in different languages, with different CPU architectures, that question becomes the whole problem.</p><p>How does process A send an integer to process B if one stores it big-endian and the other stores it little-endian? How does a Python client talk to a Java server? How does a web browser call a remote service at all?</p><p>The answer is <strong>external data representation and marshalling</strong> — and honestly, it’s one of those concepts that sounds dry until you realise everything from Netflix to your university student portal depends on it.</p><h3>What is Marshalling, Anyway?</h3><p>Before data can travel across a network, it needs to be flattened into a stream of bytes. A struct in memory has pointers, nested references, maybe cyclic links — none of that survives a network hop as-is. <strong>Marshalling</strong> is the process of assembling data into a transmittable form. <strong>Unmarshalling</strong> is the reverse: reconstructing the original data structure at the destination.</p><p>Think of it like packing a suitcase. The suitcase (byte stream) has to fit through airport security (the network) and then be unpacked the same way at the other end — even if the person unpacking doesn’t know exactly how you fold things.</p><p>Three main approaches have emerged in distributed systems, each with very different design philosophies.</p><h3>CORBA CDR — Built for Heterogeneous Systems</h3><p>CORBA (Common Object Request Broker Architecture) was developed in the early 1990s to let objects written in <em>any</em> language communicate with each other. Its serialisation format is called <strong>CDR — Common Data Representation</strong>.</p><p>CDR is a <strong>binary format</strong>. Integers, floats, strings — all encoded directly as bytes according to a strict specification. One clever detail: CDR includes a flag in the message header to indicate whether the data was serialised in big-endian or little-endian byte order. The receiver adapts accordingly, so you never have a silent byte-swap bug.</p><p>Types are defined upfront in <strong>IDL (Interface Definition Language)</strong>, a language-neutral interface description. The IDL compiler generates stub code for both sender and receiver, so the actual marshalling logic is auto-generated — you just write your business logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*bvOIdsg0m8cHdosrWr1PPA.png" /></figure><p>The receiver gets a clean double regardless of whether the sender was a C++ process or a COBOL legacy system.</p><p><strong>Where it shines:</strong> Heterogeneous enterprise environments — think banking systems where a Java front-end talks to a C++ core. CDR is compact, fast, and doesn’t waste bytes.</p><p><strong>Where it falls short:</strong> The IDL-first workflow feels rigid compared to modern approaches. CORBA as an ecosystem is largely considered legacy today, but CDR’s design ideas live on in formats like Protocol Buffers.</p><h3>Java Object Serialisation — Convenient, but Opinionated</h3><p>Java’s built-in serialisation mechanism takes a very different approach. Rather than requiring you to define types in a separate IDL, it uses <strong>reflection</strong> to automatically inspect any object and flatten it to bytes. If your class implements Serializable, Java handles the rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*CP5Rw8wfLTeNjjXGoxw0IA.png" /></figure><p>That serialVersionUID field is important. It acts as a version stamp. If you change the class structure — add a field, rename something — and the UID doesn&#39;t match what was serialised, you&#39;ll get an InvalidClassException. This is Java&#39;s way of protecting against loading stale data into an incompatible class definition.</p><p>Java serialisation also handles <strong>object graphs</strong> — if your object contains references to other objects, and those objects reference back, it traverses the whole graph correctly without getting into infinite loops.</p><p><strong>Where it shines:</strong> Internal Java-to-Java communication. RMI (Remote Method Invocation) uses it heavily. You can serialise complex object hierarchies with almost no boilerplate.</p><p><strong>Where it falls short:</strong> It’s completely Java-locked. A Python service cannot deserialise a Java object stream without heroic effort. There are also well-documented security vulnerabilities — deserialising untrusted data in Java is considered dangerous enough that modern Java projects often avoid it entirely in favour of formats like JSON or Protocol Buffers.</p><h3>XML — The Human-Readable Compromise</h3><p>XML took a completely different philosophy: instead of compactness, prioritise readability and interoperability. An XML message is plain text that any language, any tool, any human can open and read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*TgUNTl4cT_WIiDVXK4r2KA.png" /></figure><p>In distributed systems, XML found its biggest application in <strong>SOAP web services</strong> — the predecessor to REST APIs. A SOAP message is literally an XML envelope wrapping the data, and the schema is defined separately in a WSDL (Web Services Description Language) file.</p><p>XML is <strong>self-describing</strong>: the tags carry the field names alongside the values, so a receiver can parse the message even without a pre-shared schema definition. You can also validate messages against an XSD schema for strict type checking.</p><p><strong>Where it shines:</strong> Web services where interoperability is the first priority and performance is secondary. Also anywhere where auditability matters — an XML log file is readable by a human without any special tools.</p><p><strong>Where it falls short:</strong> Verbosity. Compared to binary formats, XML wastes enormous amounts of bytes on tags that repeat for every message. Parsing XML is also CPU-intensive relative to binary alternatives. For high-throughput, low-latency systems, XML rarely makes sense today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*5xIZyO4d9wKPWWXJf8qNrA.png" /></figure><h3>Going Further — What’s Used Today?</h3><p>It’s worth knowing that CDR, Java serialisation, and XML are foundational concepts — real production systems in 2024 tend to use more modern derivatives.</p><p><strong>Protocol Buffers (protobuf)</strong> by Google are conceptually similar to CORBA CDR: define your schema in a .proto file, compile it to stubs, send compact binary messages. But the tooling is far better and the ecosystem covers every major language.</p><p><strong>MessagePack</strong> is sometimes called “binary JSON” — it keeps JSON’s schema-free flexibility but encodes values in binary for a significant size reduction.</p><p><strong>Apache Avro</strong> takes yet another approach: the schema is embedded alongside the data or shared via a schema registry, which makes it popular in streaming systems like Apache Kafka where producers and consumers evolve independently.</p><h3>Closing Thoughts</h3><p>What struck me most revisiting this lecture material is how each approach reflects the priorities of its era. CORBA CDR was designed when heterogeneous enterprise systems were the hard problem. Java serialisation came from a world where Java was expected to be universal. XML emerged when web interoperability between unknown parties was the challenge to solve.</p><p>None of them is universally “right.” A system moving terabytes of IoT sensor data wants binary compactness. A system integrating with a government API built in 2005 might have no choice but XML. An internal microservice cluster in Java might still find Java serialisation acceptable — though most teams would reach for protobuf or JSON first.</p><p>Understanding the tradeoffs here is less about memorising specs and more about developing the judgment to ask: <em>who is sending this, who is receiving it, and what do we value more — speed, readability, or flexibility?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5273e6db472" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Reengineering: Modernizing Systems Without Starting From Scratch]]></title>
            <link>https://medium.com/@tthushakaran19/software-reengineering-modernizing-systems-without-starting-from-scratch-3d92804041dd?source=rss-de037e479219------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d92804041dd</guid>
            <category><![CDATA[reengineering-software]]></category>
            <dc:creator><![CDATA[Thushakaran Balasubramaniyam]]></dc:creator>
            <pubDate>Sun, 10 May 2026 09:00:13 GMT</pubDate>
            <atom:updated>2026-05-10T09:00:13.959Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the current world of technology, software systems don’t stay modern for long. Many organizations still rely on systems that were developed years ago. These systems, often called legacy systems, are still useful, but they can be difficult to maintain, slow, and not compatible with newer technologies.</p><p>Replacing such systems completely is not always a good idea because it can be expensive and risky. This is where software reengineering becomes important. Instead of building a new system from the beginning, reengineering focuses on improving the existing system while keeping its core functionality the same.</p><p>In this article, I will explain what software reengineering is, why it is important, how the process works, tools used, real-world applications, and future trends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*E3YTygQE62ac5qwf" /></figure><h3>What is Software Reengineering?</h3><p>Software reengineering is the process of modifying an existing software system to improve its quality, structure, performance, and maintainability without changing its external behavior.</p><p>In simple terms, it is like renovating an old house instead of demolishing it and building a new one. The structure remains, but improvements are made to make it modern and efficient.</p><p>For example, a company may still use an old payroll system built in COBOL. Even though it works correctly, it is hard to maintain and integrate with modern systems. Instead of rewriting everything, developers can reengineer it into Java or a cloud-based system while preserving its core business logic.</p><h3>Why is Software Reengineering Important?</h3><p>Software reengineering is widely used in organizations because of several advantages:</p><h4>Cost Saving</h4><p>Developing a completely new system requires significant time and financial investment. Reengineering reduces this cost by reusing existing logic and components.</p><h4>Lower Risk</h4><p>Legacy systems often contain well-tested business logic. Rewriting from scratch may introduce new bugs or failures. Reengineering reduces this risk.</p><h4>Better Maintainability</h4><p>Old systems are often difficult to understand due to poor structure or missing documentation. Reengineering improves readability and structure.</p><h4>Technology Upgrade</h4><p>It allows systems to be modernized using cloud computing, microservices, and modern programming languages.</p><h4>Business Continuity</h4><p>Since the system is improved rather than replaced, business operations continue without major disruption.</p><h3>Software Reengineering Process</h3><p>The software reengineering process is structured into several key stages:</p><h4>1. Inventory Analysis</h4><p>This step identifies which systems are worth reengineering. Organizations evaluate cost, importance, and complexity before deciding.</p><h4>2. Document Restructuring</h4><p>Many legacy systems lack proper documentation. This step involves creating or updating documentation to reflect the actual system behavior.</p><h4>3. Reverse Engineering</h4><p>Reverse engineering is used to understand how the system works by analyzing existing code and extracting design information.</p><h4>4. Code Restructuring</h4><p>The code is cleaned and optimized without changing functionality. This includes removing dead code, improving naming conventions, and organizing modules.</p><h4>5. Data Restructuring</h4><p>Old databases and data formats are updated to modern standards such as relational or cloud-based databases.</p><h4>6. Forward Engineering</h4><p>Finally, the system is rebuilt or upgraded using modern technologies based on improved design and structure.</p><h3>Reverse Engineering</h3><p>Reverse engineering is one of the most critical parts of software reengineering. It focuses on understanding the system rather than modifying it directly.</p><h4>Why it is needed</h4><ul><li>To understand system functionality</li><li>To recover missing documentation</li><li>To identify system architecture</li><li>To detect design flaws</li></ul><h4>Example:</h4><p>If a company has a payroll system with no documentation, developers can analyze the source code and generate UML diagrams to understand relationships between modules such as salary calculation, tax deduction, and employee management.</p><p>Reverse engineering is especially useful when original developers are no longer available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2HOdjjvNrM1e5qvX" /></figure><h3>Models of Software Reengineering</h3><p>There are different ways to approach reengineering.</p><h4>Incremental Model</h4><p>The system is improved step by step. This is safer because changes are made gradually.</p><h4>Big Bang Model</h4><p>The entire system is reengineered at once. This is faster but risky.</p><h4>Evolutionary Model</h4><p>The system is continuously improved over time with small updates.</p><p>Among these, the incremental model is commonly used because it balances risk and progress.</p><h3>Real-World Applications of Software Reengineering</h3><p>Software reengineering is widely used across industries:</p><h4>Banking Systems</h4><p>Banks often use decades-old systems for transactions. These systems are reengineered to support mobile banking and online services.</p><h4>Airline Reservation Systems</h4><p>Older reservation systems are upgraded to handle real-time bookings and cloud scalability.</p><h4>Government Systems</h4><p>Many government systems are modernized to improve efficiency and reduce manual processing.</p><h4>Healthcare Systems</h4><p>Hospitals reengineer patient record systems to integrate electronic health records (EHR) and improve accessibility.</p><h3>Tools Used in Software Reengineering</h3><p>Modern tools make the reengineering process easier and faster.</p><h4>Code Analysis Tools</h4><p>These tools help identify problems in the code.<br> Example: SonarQube</p><h4>Reverse Engineering Tools</h4><p>Used to generate system diagrams from code.<br> Example: Enterprise Architect</p><h4>Refactoring Tools</h4><p>Help improve code structure without changing behavior.<br> Examples: IntelliJ IDEA, Eclipse</p><h4>Migration Tools</h4><p>Used to move systems to modern platforms.<br> Example: AWS Migration Hub</p><h3>Challenges in Software Reengineering</h3><p>Despite its advantages, reengineering has several challenges:</p><h4>Lack of Documentation</h4><p>Many legacy systems have incomplete or outdated documentation.</p><h4>Complex Codebase</h4><p>Older systems often contain tightly coupled and messy code.</p><h4>Hidden Dependencies</h4><p>Some system components depend on others in undocumented ways.</p><h4>Skill Gap</h4><p>Developers must understand both old technologies (like COBOL) and modern systems (like cloud computing).</p><h4>Resistance to Change</h4><p>Organizations may hesitate to modify systems that are already working.</p><h3>Best Practices for Successful Reengineering</h3><p>To improve success rate, organizations follow these practices:</p><ul><li>Start with small, low-risk modules</li><li>Maintain proper documentation during the process</li><li>Use automated tools for analysis and refactoring</li><li>Involve experienced developers familiar with legacy systems</li><li>Test continuously during each stage</li></ul><h3>Future Directions</h3><p>Software reengineering is evolving with new technologies.</p><h4>AI-Based Tools</h4><p>Artificial intelligence can help analyze and improve code automatically.</p><h4>Cloud Migration</h4><p>Many systems are being moved to the cloud for better performance and scalability.</p><h4>Microservices Architecture</h4><p>Large systems are being divided into smaller services, making them easier to manage.</p><h4>Automation</h4><p>More automated tools are being developed to reduce manual effort.</p><h4>Continuous Modernization</h4><p>Instead of one-time updates, systems are continuously improved over time.</p><h3>Conclusion</h3><p>Software reengineering is an important approach for improving existing systems without starting from scratch. It allows organizations to reduce costs, lower risks, and extend the life of legacy systems.</p><p>While challenges such as complex code and missing documentation exist, the benefits make it a practical and widely used solution in the software industry.</p><p>With modern technologies such as AI, cloud computing, and automation, software reengineering is becoming more powerful and efficient.</p><p>In conclusion, software reengineering is not just about fixing old systems — it is about transforming them into modern, scalable, and maintainable solutions that can support future business needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d92804041dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis Clustering]]></title>
            <link>https://medium.com/@tthushakaran19/redis-clustering-1c545de05764?source=rss-de037e479219------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c545de05764</guid>
            <category><![CDATA[redis-clustering]]></category>
            <dc:creator><![CDATA[Thushakaran Balasubramaniyam]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 11:45:50 GMT</pubDate>
            <atom:updated>2026-04-16T11:45:50.042Z</atom:updated>
            <content:encoded><![CDATA[<h3>Powering Scalable and Reliable Distributed Systems</h3><p>In today’s world of large-scale applications, handling millions of users and massive data efficiently is no longer optional — it’s a necessity. Technologies like Redis Clustering play a key role in making this possible. This article explores what Redis Clustering is, how it is used in real-world systems, what type of distributed system it represents, and how it satisfies the essential properties of distributed systems.</p><h3>What is Redis Clustering?</h3><p>Redis is an in-memory data store widely used for caching, real-time analytics, and high-speed data access. While a single Redis instance is fast, it has limitations in terms of memory and scalability. This is where Redis Clustering comes in.</p><p>Redis Clustering is a distributed implementation of Redis that allows data to be automatically partitioned (sharded) across multiple nodes. Instead of storing all data on a single server, Redis Cluster divides data into smaller portions and distributes them across multiple machines.</p><p>Each node in the cluster is responsible for a subset of the data, and together they form a unified system. The cluster also supports replication, where each master node has replica nodes for backup and fault tolerance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOVqek2O2adHeV9NDiPldw.png" /><figcaption>Redis clustering architecture explained visually</figcaption></figure><h3>How Redis Clustering Works</h3><p>Redis Cluster uses a concept called <strong>hash slots</strong>. There are 16,384 hash slots, and each key stored in Redis is mapped to one of these slots. These slots are then distributed across cluster nodes.</p><p>For example:-</p><ul><li>Node A → Slots 0–5000</li><li>Node B → Slots 5001–10000</li><li>Node C → Slots 10001–16383</li></ul><p>When a client sends a request, Redis determines which node holds the required slot and routes the request accordingly.</p><p>Additionally</p><ul><li>Each master node can have one or more replicas.</li><li>If a master node fails, a replica is automatically promoted to master.</li><li>Nodes communicate with each other using a gossip protocol to maintain cluster state.</li></ul><h3>Real-World Use Cases of Redis Clustering</h3><p>Redis Clustering is widely used in modern distributed applications where speed and scalability are critical.</p><p><strong>1. Caching in Web Applications</strong></p><p>Large platforms like e-commerce websites use Redis Cluster to cache frequently accessed data such as product details or user sessions. This reduces database load and improves response time.</p><p><strong>2. Real-Time Analytics</strong></p><p>Applications that process streaming data — like dashboards or monitoring systems — use Redis Cluster to handle high-speed read/write operations.</p><p><strong>3. Session Management</strong></p><p>In distributed web systems, user sessions need to be shared across multiple servers. Redis Cluster ensures session data is consistently available regardless of which server handles the request.</p><p><strong>4. Gaming Systems</strong></p><p>Online multiplayer games rely on Redis Cluster for leaderboards, player states, and matchmaking due to its low latency.</p><h3>Type of Distributed System</h3><p>Redis Clustering represents a <strong>peer-to-peer distributed system</strong> with elements of <strong>client-server architecture</strong>.</p><ul><li>Each node (master or replica) can communicate with other nodes directly.</li><li>There is no single central coordinator; instead, the cluster manages itself.</li><li>Clients interact with the cluster as a unified system.</li></ul><p>According to distributed system classifications, Redis Cluster fits into:</p><ul><li><strong>Data-intensive distributed systems</strong></li><li><strong>Scalable cloud-based systems</strong></li><li><strong>Peer-to-peer systems (partially)</strong></li></ul><p>This aligns with the definition of distributed systems where components communicate through message passing and operate concurrently without a global clock</p><h3>How Redis Clustering Preserves the Seven Desired Properties</h3><p>Distributed systems are expected to satisfy several key properties. Redis Clustering addresses these effectively</p><p><strong>1. Fault Tolerance</strong></p><p>Fault tolerance means the system continues functioning even when some components fail.</p><p>Redis Cluster achieves this through</p><ul><li>Replication (master–replica model)</li><li>Automatic failover</li></ul><p>If a master node crashes, a replica is promoted to take over. This ensures that the system continues operating without data loss.</p><p><strong>2. High Availability</strong></p><p>High availability ensures the system remains accessible even during failures.</p><p>Redis Cluster maintains availability by</p><ul><li>Distributing data across multiple nodes</li><li>Promoting replicas when failures occur</li></ul><p>Even if one node goes down, the rest of the cluster continues serving requests.</p><p><strong>3. Recoverability</strong></p><p>Recoverability refers to the system’s ability to restore failed components.</p><p>In Redis Cluster</p><ul><li>Failed nodes can rejoin the cluster after recovery</li><li>Data is synchronized from replicas or other nodes</li></ul><p>This allows the system to return to a consistent state after failures.</p><p><strong>4. Consistency</strong></p><p>Consistency ensures all nodes reflect correct and up-to-date data.</p><p>Redis Cluster provides <strong>eventual consistency</strong></p><ul><li>Writes are handled by master nodes</li><li>Replicas asynchronously receive updates</li></ul><p>While there may be slight delays, the system ensures that all nodes eventually converge to the same state.</p><p><strong>5. Scalability</strong></p><p>Scalability is one of Redis Cluster’s strongest features.</p><p>It supports</p><ul><li>Horizontal scaling by adding more nodes</li><li>Automatic rebalancing of hash slots</li></ul><p>As demand increases, new nodes can be added without significant system redesign, which aligns with the scalability definition in distributed systems .</p><p><strong>6. Predictable Performance</strong></p><p>Predictable performance means the system responds within expected time limits.</p><p>Redis Cluster ensures this by</p><ul><li>Using in-memory storage for fast operations</li><li>Distributing load across nodes</li><li>Avoiding bottlenecks through sharding</li></ul><p>This results in consistently low latency even under heavy load.</p><p><strong>7. Security</strong></p><p>Security involves protecting data and ensuring authorized access.</p><p>Redis Cluster supports:</p><ul><li>Authentication mechanisms (password-based)</li><li>Network-level security (firewalls, TLS in modern setups)</li></ul><p>Although Redis is not primarily a security-focused system, it integrates well with secure infrastructures to ensure confidentiality and integrity.</p><h3>Challenges in Redis Clustering</h3><p>Despite its advantages, Redis Cluster also faces challenges</p><p><strong>1. Complexity</strong></p><p>Setting up and managing a cluster is more complex than a single Redis instance.</p><p><strong>2. Data Partitioning Issues</strong></p><p>Improper key distribution can lead to uneven load across nodes.</p><p><strong>3. Eventual Consistency Trade-offs</strong></p><p>Some applications require strong consistency, which Redis Cluster does not fully guarantee.</p><p><strong>4. Network Dependency</strong></p><p>Since nodes communicate over a network, latency and failures can affect performance.</p><p>These challenges reflect general distributed system issues such as heterogeneity, failure handling, and concurrency</p><h3>Why Redis Clustering Matters</h3><p>Redis Clustering is a great example of how modern systems handle scale and reliability. It demonstrates key distributed system concepts such as</p><ul><li>No global clock (nodes operate independently)</li><li>Concurrent processing</li><li>Independent failures</li></ul><p>These characteristics are fundamental to distributed systems and are clearly visible in Redis Cluster’s design</p><h3>Conclusion</h3><p>Redis Clustering is a powerful distributed technology that enables high-performance, scalable, and fault-tolerant systems. By distributing data across multiple nodes and ensuring redundancy through replication, it meets the demands of modern applications.</p><p>It represents a practical implementation of distributed system principles, successfully addressing key properties like fault tolerance, availability, scalability, and performance. While it comes with certain trade-offs, its benefits make it a popular choice for real-time and large-scale applications.</p><p>As systems continue to grow in complexity and scale, technologies like Redis Clustering will remain essential in building efficient and reliable distributed architectures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c545de05764" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Secure E-Commerce Platform]]></title>
            <link>https://medium.com/@tthushakaran19/building-a-secure-e-commerce-platform-8b69f3e9d578?source=rss-de037e479219------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b69f3e9d578</guid>
            <dc:creator><![CDATA[Thushakaran Balasubramaniyam]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 14:47:19 GMT</pubDate>
            <atom:updated>2025-09-06T06:56:09.221Z</atom:updated>
            <content:encoded><![CDATA[<p>A Deep Dive into OIDC Authentication and OWASP Security Implementation</p><p><em>How I built a production-ready e-commerce application with enterprise-grade security features.</em></p><h4>Introduction</h4><p>In today’s digital landscape, security is not just a feature — it’s a fundamental requirement. As web applications become more sophisticated and handle increasingly sensitive data, implementing robust security measures has become paramount. This article explores the development of a secure e-commerce platform that demonstrates best practices in authentication, authorization, and comprehensive security implementation.</p><p>The project showcases a full-stack e-commerce application built with modern technologies, featuring OIDC (OpenID Connect) authentication, comprehensive OWASP Top 10 security measures, and a sophisticated order management system. Let’s dive into the technical architecture and security implementations that make this application production ready.</p><h4>Project Overview</h4><p><strong><em>Frontend</em></strong></p><p>- React.js with Vite for fast development and optimized builds</p><p>- Redux Toolkit for predictable state management</p><p>- Tailwind CSS for responsive, utility-first styling</p><p>- React Hook Form for efficient form handling</p><p>-React Router for client-side navigation</p><p><strong><em>Backend</em></strong></p><p>- Node.js with Express.js for the server framework</p><p>- MongoDB with Mongoose for data persistence</p><p>- Passport.js for authentication strategies</p><p>- JWT for secure token-based authentication</p><p>- Helmet for security headers</p><p>-Express Rate Limit for DDoS protection</p><p><strong><em>Security &amp; Authentication</em></strong></p><p>- Auth0 for OIDC provider</p><p>- OAuth2/OIDC flow implementation</p><p>- JWT token management</p><p>- Comprehensive input validation and sanitization</p><h4>Architecture Deep Dive</h4><p><strong>1. Authentication Flow: OIDC Implementation</strong></p><p>The application implements a sophisticated OIDC authentication flow that provides enterprise-grade security:</p><p>JavaScript</p><p><em>OAuth2 Strategy Configuration</em></p><p>const oauth2Strategy = new OAuth2Strategy(</p><p>{</p><p>authorizationURL: `https://${process.env.OIDC_DOMAIN}/authorize`,</p><p>tokenURL: `https://${process.env.OIDC_DOMAIN}/oauth/token`,</p><p>clientID: process.env.OIDC_CLIENT_ID,</p><p>clientSecret: process.env.OIDC_CLIENT_SECRET,</p><p>callbackURL: process.env.OIDC_CALLBACK_URL,</p><p>scope: “openid profile email”,</p><p>},</p><p>async (<em>accessToken</em>, <em>refreshToken</em>, <em>profile</em>, <em>done</em>) =&gt; {</p><p><em>// User creation/update logic</em></p><p>const userInfo = {</p><p>oidcId: profile.id,</p><p>oidcProvider: “auth0”,</p><p>name: profile.displayName,</p><p>email: profile.emails?.[0]?.value,</p><p>username: profile.username || profile.emails?.[0]?.value?.split(“@”)[0],</p><p>accessToken: accessToken,</p><p>refreshToken: refreshToken,</p><p>tokenExpiry: new Date(Date.now() + 3600000),</p><p>};</p><p><em>// Find or create user logic</em></p><p>let user = await User.findOne({ oidcId: profile.id });</p><p>if (!user) {</p><p>user = new User(userInfo);</p><p>await user.save();</p><p>}</p><p>return done(null, user);</p><p>}</p><p>);</p><p>Key Benefits of OIDC Implementation</p><p>-Standardized Authentication: Uses industry-standard OIDC protocol</p><p>- Single Sign-On (SSO): Enables seamless authentication across multiple applications</p><p>- Enhanced Security: Leverages Auth0’s robust security infrastructure</p><p>- Scalability: Supports enterprise-level user management</p><p><strong>2. Security Middleware: OWASP Top 10 Compliance</strong></p><p>The application implements comprehensive security measures addressing all OWASP Top 10 vulnerabilities:</p><p><em>Rate Limiting Implementation</em></p><p>JavaScript</p><p>const createRateLimiter = (<em>windowMs</em>, <em>max</em>, <em>message</em>) =&gt; {</p><p>return rateLimit({</p><p>windowMs: windowMs,</p><p>max: max,</p><p>message: { error: message },</p><p>standardHeaders: true,</p><p>legacyHeaders: false,</p><p>});</p><p>};</p><p><em>// Different rate limits for different endpoints</em></p><p>const generalRateLimiter = createRateLimiter(15 * 60 * 1000, 100); <em>// 100 requests per 15 minutes</em></p><p>const authRateLimiter = createRateLimiter(15 * 60 * 1000, 5); <em>// 5 auth attempts per 15 minutes</em></p><p>Input Sanitization and Validation</p><p>JavaScript</p><p>const sanitizeInput = (<em>req</em>, <em>res</em>, <em>next</em>) =&gt; {</p><p>if (req.body) {</p><p>Object.keys(req.body).forEach((<em>key</em>) =&gt; {</p><p>if (typeof req.body[key] === “string”) {</p><p>req.body[key] = sanitizeHtml(req.body[key], {</p><p>allowedTags: [],</p><p>allowedAttributes: {},</p><p>});</p><p>}</p><p>});</p><p>}</p><p>next();</p><p>};</p><p><em>// Comprehensive validation rules</em></p><p>const orderValidationRules = [</p><p>body(“purchaseDate”)</p><p>.isISO8601()</p><p>.withMessage(“Valid purchase date is required”),</p><p>body(“deliveryTime”)</p><p>.isIn([“10 AM”, “11 AM”, “12 PM”])</p><p>.withMessage(“Valid delivery time is required”),</p><p>body(“quantity”)</p><p>.isInt({ min: 1, max: 10 })</p><p>.withMessage(“Quantity must be between 1 and 10”),</p><p>body(“message”)</p><p>.optional()</p><p>.isLength({ max: 500 })</p><p>.withMessage(“Message cannot exceed 500 characters”),</p><p>];</p><p>Security Headers Configuration</p><p>JavaScript</p><p>const securityHeaders = helmet({</p><p>contentSecurityPolicy: {</p><p>directives: {</p><p>defaultSrc: [“‘self’”],</p><p>styleSrc: [“‘self’”, “‘unsafe-inline’”],</p><p>scriptSrc: [“‘self’”],</p><p>imgSrc: [“‘self’”, “data:”, “https:”],</p><p>connectSrc: [“‘self’”],</p><p>fontSrc: [“‘self’”],</p><p>objectSrc: [“‘none’”],</p><p>mediaSrc: [“‘self’”],</p><p>frameSrc: [“‘none’”],</p><p>},</p><p>},</p><p>hsts: {</p><p>maxAge: 31536000,</p><p>includeSubDomains: true,</p><p>preload: true,</p><p>},</p><p>});</p><p><strong>3. Order Management System</strong></p><p>The application features a sophisticated order management system with business logic validation:</p><p>Order Creation with Business Rules</p><p>JavaScript</p><p>exports.createOrder = catchAsyncError(async (<em>req</em>, <em>res</em>, <em>next</em>) =&gt; {</p><p>const {</p><p>purchaseDate,</p><p>deliveryTime,</p><p>deliveryLocation,</p><p>productName,</p><p>quantity,</p><p>message,</p><p>} = req.body;</p><p><em>// Business rule: No Sunday deliveries</em></p><p>const selectedDate = new Date(purchaseDate);</p><p>if (selectedDate.getDay() === 0) {</p><p>return next(new ErrorHandler(“Purchase date cannot be Sunday”, 400));</p><p>}</p><p><em>// Business rule: Future dates only</em></p><p>const today = new Date();</p><p>today.setHours(0, 0, 0, 0);</p><p>selectedDate.setHours(0, 0, 0, 0);</p><p>if (selectedDate &lt; today) {</p><p>return next(</p><p>new ErrorHandler(“Purchase date must be on or after current date”, 400)</p><p>);</p><p>}</p><p><em>// Product validation and price calculation</em></p><p>const product = await Product.findOne({ name: productName });</p><p>if (!product) {</p><p>return next(new ErrorHandler(`Product ‘${productName}’ not found`, 404));</p><p>}</p><p>const totalAmount = product.price * quantity;</p><p>const order = await Order.create({</p><p>username: req.user.username,</p><p>purchaseDate,</p><p>deliveryTime,</p><p>deliveryLocation,</p><p>productName,</p><p>quantity,</p><p>message,</p><p>totalAmount,</p><p>});</p><p>res.status(201).json({</p><p>success: true,</p><p>message: “Order created successfully”,</p><p>order,</p><p>});</p><p>});</p><p>Access Control Implementation</p><p>JavaScript</p><p><em>// Ownership-based access control</em></p><p>const checkOwnership = (<em>resourceModel</em>) =&gt; {</p><p>return async (<em>req</em>, <em>res</em>, <em>next</em>) =&gt; {</p><p>const resource = await resourceModel.findById(req.params.id);</p><p>if (!resource) {</p><p>return res.status(404).json({</p><p>success: false,</p><p>message: “Resource not found”,</p><p>});</p><p>}</p><p><em>// Critical security check: Users can only access their own resources</em></p><p>if (resource.username !== req.user.username) {</p><p>return res.status(403).json({</p><p>success: false,</p><p>message: “Access denied. You can only access your own resources.”,</p><p>});</p><p>}</p><p>req.resource = resource;</p><p>next();</p><p>};</p><p>};</p><p><strong>4. Frontend State Management</strong></p><p>The React frontend uses Redux Toolkit for predictable state management:</p><p>JavaScript</p><p><em>// Redux store configuration</em></p><p>export const store = configureStore({</p><p>reducer: {</p><p>user: userReducer,</p><p>products: productReducer,</p><p>cart: cartReducer,</p><p>order: orderReducer,</p><p>},</p><p>middleware: (<em>getDefaultMiddleware</em>) =&gt;</p><p>getDefaultMiddleware({</p><p>serializableCheck: {</p><p>ignoredActions: [“persist/PERSIST”],</p><p>},</p><p>}),</p><p>});</p><h4>Order Management Component</h4><p>The Orders component demonstrates sophisticated form handling and validation:</p><p>JavaScript</p><p>const Orders = () =&gt; {</p><p>const {</p><p>register,</p><p>handleSubmit,</p><p>formState: { errors },</p><p>reset,</p><p>watch,</p><p>} = useForm();</p><p>const watchedDate = watch(“purchaseDate”);</p><p><em>// Dynamic delivery time availability</em></p><p>useEffect(() =&gt; {</p><p>if (watchedDate) {</p><p>const date = new Date(watchedDate);</p><p>setSelectedDate(date);</p><p>dispatch(getAvailableDeliveryTimes(date.toISOString().split(“T”)[0]));</p><p>}</p><p>}, [watchedDate, dispatch]);</p><p><em>// Sunday filtering for date picker</em></p><p>const filterSundays = (<em>date</em>) =&gt; {</p><p>return date.getDay() !== 0; <em>// 0 is Sunday</em></p><p>};</p><p>return (</p><p>&lt;DatePicker</p><p><em>selected</em>={selectedDate}</p><p><em>onChange</em>={(<em>date</em>) =&gt; setSelectedDate(date)}</p><p><em>filterDate</em>={filterSundays}</p><p><em>minDate</em>={new Date()}</p><p><em>dateFormat</em>=”yyyy-MM-dd”</p><p><em>className</em>=”mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm”</p><p><em>placeholderText</em>=”Select date”</p><p>{…register(“purchaseDate”, {</p><p>required: “Purchase date is required”,</p><p>})}</p><p>/&gt;</p><p>);</p><p>};</p><h4>Security Features Breakdown</h4><p><strong>1. Broken Access Control Prevention</strong></p><p>- Ownership-based Access Control: Users can only access their own orders and profile data</p><p>- Resource-level Authorization: Every API endpoint validates user ownership</p><p>- Role-based Access: JWT tokens contain user identification for authorization</p><p><strong>2. Cryptographic Failures Mitigation</strong></p><p>- HTTPS Enforcement: All production traffic encrypted</p><p>- Secure JWT Implementation: Tokens signed with strong secrets</p><p>- Password Hashing: bcrypt for secure password storage</p><p>- Token Expiration: Automatic token expiry and refresh mechanisms</p><p><strong>3. Injection Attack Prevention</strong></p><p>- Input Sanitization: All user inputs sanitized using sanitize-html</p><p>- Parameterized Queries: Mongoose ODM prevents NoSQL injection</p><p>- Validation Middlewar: Express-validator for comprehensive input validation</p><p><strong>4. Insecure Design Mitigation</strong></p><p>- Security-first Architecture: Security considerations from design phase</p><p>- Defense in Depth: Multiple layers of security controls</p><p>- Fail-secure Defaults: Secure defaults for all configurations</p><p><strong>5. Security Misconfiguration Prevention</strong></p><p>- Security Headers: Helmet.js for comprehensive security headers</p><p>- CORS Configuration: Proper cross-origin resource sharing setup</p><p>- Environment Variables: Sensitive data externalized from code</p><p><strong>6. Vulnerable Components Management</strong></p><p>- Dependency Updates: Regular updates of all dependencies</p><p>- Security Auditing: npm audit for vulnerability detection</p><p>- Minimal Dependencies: Only necessary packages included</p><p><strong>7. Authentication Failures Prevention</strong></p><p>- OIDC Implementation: Industry-standard authentication protocol</p><p>- Multi-factor Ready: Auth0 supports MFA out of the box</p><p>- Session Management: Secure session handling with proper expiration</p><p><strong>8. Software and Data Integrity</strong></p><p>- Input Validation: Comprehensive validation on all inputs</p><p>- Data Sanitization: XSS prevention through input sanitization</p><p>- File Upload Security: Secure file handling with validation</p><p><strong>9. Security Logging and Monitoring</strong></p><p>- Request Logging: Comprehensive logging of all requests</p><p>- Error Handling: Structured error responses without information leakage</p><p>- Audit Trails: User actions logged for security monitoring</p><p><strong>10. Server-Side Request Forgery Prevention</strong></p><p>- CORS Configuration: Proper cross-origin request handling</p><p>- Input Validation: Validation of all external requests</p><ul><li>Network Security: Restricted network access patterns</li></ul><h4>Business Logic Implementation</h4><p><strong>Order Management Features</strong></p><p>1. Date Validation:</p><p>- No Sunday deliveries</p><p>- Future dates only</p><p>- Business day restrictions</p><p>2. Delivery Time Management:</p><p>- Limited time slots (10 AM, 11 AM, 12 PM)</p><p>- Capacity management (max 5 orders per time slot)</p><p>- Real-time availability checking</p><p>3. Geographic Restrictions:</p><p>- Sri Lankan districts only</p><p>- Location-based delivery validation</p><p>4. Product Management:</p><p>- Predefined product catalog</p><p>- Quantity limits (1–10 items)</p><p>- Price calculation with validation</p><p>5. Order Status Tracking:</p><p>- Pending, Confirmed, Shipped, Delivered, Cancelled</p><p>- Status-based business rules</p><p>- Cancellation restrictions (pending orders only)</p><p>Performance and Scalability Considerations</p><h4>Production Environment Variables</h4><p>NODE_ENV=production</p><p>PORT=5000</p><p>MONGO_URI=your_production_mongodb_uri</p><p>JWT_SECRET=your_production_jwt_secret</p><h4>HTTPS Configuration</h4><p>HTTPS_KEY_PATH=./ssl/private.key</p><p>HTTPS_CERT_PATH=./ssl/certificate.crt</p><h4>OIDC Configuration</h4><p>OIDC_CLIENT_ID=your_auth0_client_id</p><p>OIDC_CLIENT_SECRET=your_auth0_client_secret</p><p>OIDC_DOMAIN=your_auth0_domain.auth0.com</p><h4>Conclusion</h4><p>Building a secure e-commerce application requires careful consideration of multiple security aspects, from authentication and authorization to input validation and access control. This project demonstrates how modern web technologies can be combined with industry-standard security practices to create a robust, production-ready application.</p><p>The implementation of OIDC authentication, comprehensive OWASP Top 10 security measures, and sophisticated business logic validation creates a solid foundation for a secure e-commerce platform. The modular architecture and security-first approach ensure that the application can scale while maintaining security standards.</p><p>Key takeaways from this project:</p><p>1. **Security is not optional** — Every aspect of the application must be designed with security in mind</p><p>2. **Use established standards** — OIDC, OWASP guidelines, and industry best practices provide proven security frameworks</p><p>3. **Defense in depth** — Multiple layers of security controls provide comprehensive protection</p><p>4. **Regular testing and updates** — Security is an ongoing process that requires continuous attention</p><p>5. **User experience matters** — Security measures should enhance, not hinder, the user experience</p><p>This project serves as a comprehensive example of how to build secure web applications in the modern era, balancing security, performance, and user experience to create applications that are both secure and functional.</p><p>Technologies Used: React, Node.js, Express.js, MongoDB, Auth0, OIDC, JWT, Redux Toolkit, Tailwind CSS, Helmet.js, Express Rate Limit, and more.</p><p>Security Standards: OWASP Top 10 compliance, OIDC authentication, comprehensive input validation, and access control implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b69f3e9d578" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Software Licensing]]></title>
            <link>https://medium.com/@tthushakaran19/understanding-software-licensing-7922beb4f450?source=rss-de037e479219------2</link>
            <guid isPermaLink="false">https://medium.com/p/7922beb4f450</guid>
            <dc:creator><![CDATA[Thushakaran Balasubramaniyam]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 10:22:49 GMT</pubDate>
            <atom:updated>2024-06-24T10:22:49.371Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the rapidly evolving world of software development, understanding software licenses is crucial. Software licenses dictate how software can be used, modified, and distributed. In this blog, we’ll delve into the various types of software licenses, their implications, and key concepts such as copyright law and the distinction between ownership and licensing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*lHcKKnF6wG_6hpHP.jpeg" /><figcaption>Software license</figcaption></figure><h3>What is a Software License?</h3><p>A software license is a legal instrument that governs the usage and redistribution of software. It specifies the rights and restrictions imposed on the software user, which can range from allowing free usage and modification to imposing strict limitations.</p><h3>Types of Software Licenses</h3><p>There are several types of software licenses, each with its own set of rules and freedoms.</p><p><strong>1.Public Domain License</strong></p><ul><li><strong>Description:</strong> Software in the public domain can be used, modified, and distributed by anyone without any restrictions.</li><li><strong>Example:</strong> SQLite</li></ul><p><strong>2. Lesser General Public License (LGPL)</strong></p><ul><li><strong>Description:</strong> Allows linking to open-source libraries and code can be licensed under any license type.</li><li><strong>Example:</strong> GNU LGPL</li></ul><p><strong>3. Permissive Licenses</strong></p><ul><li><strong>Description:</strong> These licenses have minimal restrictions, allowing software to be freely used, modified, and distributed, often with the condition of maintaining attribution to the original authors.</li><li><strong>Examples:</strong> MIT License, Apache License 2.0</li></ul><p><strong>4. Copyleft Licenses</strong></p><ul><li><strong>Description:</strong> These licenses require that any modified versions of the software also be distributed under the same license, ensuring that the code remains free and open.</li><li><strong>Examples:</strong> GNU General Public License (GPL), Affero General Public License (AGPL)</li></ul><p><strong>5. Proprietary Licenses</strong></p><ul><li><strong>Description:</strong> These are the most restrictive licenses. They do not allow the software to be copied, modified, or distributed without explicit permission from the copyright holder.</li><li><strong>Example:</strong> Microsoft Windows EULA</li></ul><h3>Copyright Law</h3><p>Copyright law is the foundation of software licensing. It grants the creator of the software exclusive rights to use and distribute it. Software licenses are a way for copyright holders to grant permissions to others, specifying what is and isn’t allowed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KMY1aT1mab3PFO2p" /><figcaption>Copyright Law</figcaption></figure><h3>Ownership vs Licensing</h3><p>Understanding the difference between ownership and licensing is essential.</p><ul><li><strong>Ownership:</strong> When you own software, you have the right to use, modify, and distribute it as you see fit. This is common with software you develop yourself.</li><li><strong>Licensing:</strong> When you license software, you are granted specific rights to use it under certain conditions. The licensor retains ownership and can impose restrictions on usage.</li></ul><h3>Conclusion</h3><p>Software licenses play a pivotal role in the software development ecosystem. By understanding the different types of licenses and their implications, developers and users can make informed decisions about how they use and distribute software. Whether you’re choosing a license for your own project or evaluating the license of third-party software, this knowledge is invaluable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7922beb4f450" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stored Procedure in MySQL]]></title>
            <link>https://medium.com/@tthushakaran19/stored-procedure-in-mysql-a9ec0f69d940?source=rss-de037e479219------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9ec0f69d940</guid>
            <dc:creator><![CDATA[Thushakaran Balasubramaniyam]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 03:36:54 GMT</pubDate>
            <atom:updated>2024-02-23T03:36:54.361Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Unlocking Efficiency and Performance with Stored Procedures in MySQL</strong></p><p>In the realm of database management systems, efficiency and performance are paramount. One powerful tool in the arsenal of developers and database administrators is the use of stored procedures. These stored procedures offer a structured approach to executing repetitive tasks within a MySQL database, enhancing both productivity and scalability. In this article, we will delve into what stored procedures are, their advantages and disadvantages, how to write and execute them in MySQL, and provide an example use case to illustrate their practical.</p><h4><strong>What are Stored Procedures?</strong></h4><p>Stored procedures are precompiled SQL statements stored in the database itself. They encapsulate a series of SQL queries and procedural logic, allowing them to be executed as a single unit. Once created, stored procedures can be invoked by application code or other SQL statements, providing a modular and reusable solution for database operations.</p><h4><strong>Advantages and Disadvantages</strong></h4><p><strong><em>Advantages</em></strong></p><p>· <strong>Improved Performance</strong>: Stored procedures are precompiled and stored in memory, reducing the overhead of parsing and optimizing SQL statements with each execution.</p><p>· <strong>Enhanced Security</strong>: By granting users access only to stored procedures rather than directly to tables, you can enforce stricter access controls and mitigate the risk of SQL injection attacks.</p><p>· <strong>Code Reusability</strong>: Stored procedures promote code reuse across multiple applications and database interactions, fostering a more maintainable and scalable codebase.</p><p>· <strong>Centralized Maintenance</strong>: Updates or modifications to database logic can be made centrally within the stored procedure, ensuring consistency across applications.</p><p>· <strong>Reduced Network Traffic</strong>: Executing stored procedures reduces the amount of data transferred between the database server and client application, leading to improved network efficiency.</p><p><strong><em>Disadvantages</em></strong></p><p>· <strong>Vendor Lock-In</strong>: Stored procedures are often database-specific, potentially locking you into a particular database vendor and limiting portability.</p><p>· <strong>Complexity</strong>: Writing and maintaining stored procedures requires expertise in both SQL and procedural programming, which may introduce complexity, especially for large and intricate procedures.</p><p>· <strong>Debugging Challenges</strong>: Debugging stored procedures can be more challenging compared to debugging application code, as it often requires specialized tools and techniques.</p><p><strong>. Limited Language Support</strong>: While SQL is widely supported, the procedural language used within stored procedures may have limitations compared to general-purpose programming languages.</p><h4><strong>How to Write and Execute Stored Procedures in MySQL</strong></h4><p>MySQL supports stored procedures using the CREATE PROCEDURE statement. Below is a basic syntax for creating a stored procedure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*vtO7CSEWUODa2PErkoSl9A.png" /><figcaption>CREATE PROCEDURE statement</figcaption></figure><p>To execute a stored procedure in MySQL, you can use the CALL statement followed by the procedure name and any required parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*_v2vEBgZDD4TJAH1KHlZPA.png" /><figcaption>CALL statement</figcaption></figure><p><strong>Example Use Case:</strong></p><p>Let’s consider a scenario where we have an e-commerce platform with a MySQL database. We want to calculate the total sales revenue for a given product category within a specific time range. We can create a stored procedure named Calculate Revenue to achieve this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*9RvQhMFXEUy0aqyPXh8HOw.png" /><figcaption>Calculate Revenue</figcaption></figure><p>We can then execute this stored procedure to calculate the total revenue for a specific category within a given time range:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Rb_-Wo7w57luI4vsuSxWCw.png" /></figure><p>This stored procedure encapsulates the logic for calculating revenue, promoting code reuse and simplifying database interactions for this common task.</p><p>In conclusion, stored procedures offer a robust solution for enhancing efficiency, security, and maintainability in MySQL databases. By understanding their advantages, disadvantages, and how to effectively utilize them, developers and database administrators can leverage stored procedures to streamline database operations and unlock performance gains in their applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9ec0f69d940" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data engineer]]></title>
            <link>https://medium.com/@tthushakaran19/data-engineer-c4254ebe5b1a?source=rss-de037e479219------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4254ebe5b1a</guid>
            <dc:creator><![CDATA[Thushakaran Balasubramaniyam]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 15:54:02 GMT</pubDate>
            <atom:updated>2023-12-30T15:54:02.276Z</atom:updated>
            <content:encoded><![CDATA[<p>Data engineers work in a variety of settings to build systems that collect, manage, and convert raw data into usable information for data scientists and business analysts to interpret. Their ultimate goal is to make data accessible so that organizations can use it to evaluate and optimize their performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oJ8OeZSqcJBarVcn.jpg" /></figure><h3><strong>Data Engineer Duties and Responsibilities</strong></h3><p>In addition to creating and maintaining an optimal pipeline architecture, typical duties and responsibilities for a Data Engineer position may include</p><p>• Assembling large, complex sets of data that meet non-functional and functional business requirements</p><p>• Identifying, designing and implementing internal process improvements including re-designing infrastructure for greater scalability, optimizing data delivery, and automating manual processes</p><p>• Building required infrastructure for optimal extraction, transformation and loading of data from various data sources using AWS and SQL technologies</p><p>• Building analytical tools to utilize the data pipeline, providing actionable insight into key business performance metrics including operational efficiency and customer acquisition</p><p>• Working with stakeholders including data, design, product and executive teams and assisting them with data-related technical issues</p><h3><strong>Essential Skills</strong></h3><p><strong>1.Programming Languages</strong></p><ul><li>Proficiency in languages like Python, Java, or Scala.</li></ul><p><strong>2.SQL and Database Management</strong></p><ul><li>Strong understanding of SQL and experience with relational databases (e.g., MySQL, PostgreSQL) and non-relational databases (e.g., MongoDB, Cassandra).</li></ul><p><strong>3.ETL Tools</strong></p><ul><li>Experience with ETL tools like Apache NiFi, Talend, or Apache Beam.</li></ul><p><strong>4.Big Data Technologies</strong></p><ul><li>Familiarity with big data processing frameworks such as Apache Hadoop, Apache Spark, and Apache Kafka.</li></ul><p><strong>5.Data Modeling</strong></p><ul><li>Knowledge of data modeling techniques and tools.</li></ul><p><strong>6.Version Control</strong></p><ul><li>Proficient in version control systems like Git.</li></ul><p><strong>7.Scripting</strong></p><ul><li>Scripting skills for automation (e.g., Bash scripting).</li></ul><p><strong>8.Cloud Platforms</strong></p><ul><li>Experience with cloud platforms such as AWS, Azure, or Google Cloud.</li></ul><p><strong>9.Problem Solving</strong></p><ul><li>Strong problem-solving skills and the ability to troubleshoot issues in data processes.</li></ul><h3><strong>Preferred Skills</strong></h3><p><strong>1.Containerization and Orchestration</strong></p><ul><li>Familiarity with containerization tools like Docker and orchestration tools like Kubernetes.</li></ul><p><strong>2.Data Warehousing</strong></p><ul><li>Experience with data warehouse platforms such as Amazon Redshift, Google BigQuery, or Snowflake.</li></ul><p><strong>3.Machine Learning Basics</strong></p><ul><li>Understanding of machine learning concepts and frameworks.</li></ul><p><strong>4.Streaming Data Processing</strong></p><ul><li>Experience with streaming data processing technologies like Apache Flink or Apache Storm.</li></ul><p><strong>5.Data Governance</strong></p><ul><li>Knowledge of data governance principles and best practices.</li></ul><h3><strong>Educational Qualifications</strong></h3><ul><li>A bachelor’s degree in computer science, information technology, or a related field is typically required.</li><li>Advanced degrees (master’s or higher) may be preferred for more specialized roles or in-depth responsibilities.</li><li>Relevant certifications in cloud platforms (AWS, Azure, GCP), database technologies, and data engineering can be beneficial.</li></ul><p>It’s important to note that the specific requirements may vary based on the organization, industry, and the complexity of the data engineering tasks involved. Continuous learning and staying updated on emerging technologies are crucial in this rapidly evolving field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4254ebe5b1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>