<?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 Aditya Vandan Sharma on Medium]]></title>
        <description><![CDATA[Stories by Aditya Vandan Sharma on Medium]]></description>
        <link>https://medium.com/@van13heisenberg?source=rss-3852c29fa600------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9UCKkU5HBp3p-0NV</url>
            <title>Stories by Aditya Vandan Sharma on Medium</title>
            <link>https://medium.com/@van13heisenberg?source=rss-3852c29fa600------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 11:54:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@van13heisenberg/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[Access Tokens and Refresh Tokens: A Production Engineer’s Guide]]></title>
            <link>https://medium.com/@van13heisenberg/access-tokens-and-refresh-tokens-a-production-engineers-guide-623ec5043d10?source=rss-3852c29fa600------2</link>
            <guid isPermaLink="false">https://medium.com/p/623ec5043d10</guid>
            <category><![CDATA[authz]]></category>
            <category><![CDATA[authn]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Aditya Vandan Sharma]]></dc:creator>
            <pubDate>Sat, 30 May 2026 21:20:57 GMT</pubDate>
            <atom:updated>2026-05-30T21:20:57.387Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>HTTP is stateless. Every request arrives at the server with no inherent memory of the requests that came before it. This is fine for serving static pages, but it breaks the moment a user logs in and expects the application to remember them on the next click, the next minute, the next day.</p><p>Authentication answers a single question. Who is making this request? Authorization is the follow-up. Is this person allowed to do what they’re asking to do? These are distinct concerns. A correctly authenticated user can still be forbidden from performing an action. An unauthenticated request usually cannot get far enough to even ask.</p><p>The session continuity problem is what we’re really solving. A user types their password once. Then for the next several hours or days, every API request they make has to carry some proof that they already proved who they were. The history of web authentication is the history of figuring out what that proof should look like, where it should live, and how long it should last.</p><p>The two dominant approaches are sessions and tokens. Sessions store identity on the server and hand the client a pointer. Tokens carry identity inside the credential itself. Modern systems usually pick tokens, often a pair of them: a short-lived access token for actual API calls, and a long-lived refresh token used only to mint new access tokens. This article walks through both, end to end, with the implementation details that matter in production.</p><h3>Evolution of Session Management</h3><h4>Cookie-based sessions</h4><p>The classic web pattern stores session state on the server. When a user logs in, the server creates a session record, gives it a random opaque ID, and sends that ID back as a cookie. Every subsequent request includes the cookie, and the server looks up the record to figure out who the user is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFV74Ez83icfpAP4rfqzFg.png" /></figure><p>This approach has clean revocation semantics. Logging a user out is just deleting their session row. Forcing logout everywhere is a single SQL DELETE. There’s no cryptographic puzzle to solve.</p><p>The trouble starts when one server becomes many. If a load balancer routes requests across three application servers, an in-memory session map on server A is invisible to servers B and C. The standard fixes are sticky sessions, which tie a user to a specific server (and lose load balancing benefits and resilience), or a shared session store such as Redis, which every server hits on every authenticated request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*nh-lpAq1xForyZamVGsvTw.png" /></figure><p>Redis works. Hundreds of millions of users have authenticated through that exact topology. But it adds a hot dependency on every request, and Redis becomes a single point of failure that needs its own replication, failover, and capacity planning. Token-based authentication emerged partly to avoid this lookup on the hot path.</p><h3>Token-Based Authentication</h3><p>A token is a credential the client holds and presents on every request. The server validates the token and, if valid, treats the request as authenticated. The shape of the token determines how validation works.</p><p>Opaque tokens are random strings with no internal structure. They carry no information; the server must look them up in a database to know what they mean. Functionally they behave like session IDs with a different name.</p><p>Self-contained tokens carry their own claims inside the credential. The server validates them by checking a cryptographic signature rather than by hitting a database. JSON Web Tokens are the dominant format. They make stateless validation possible, which is the property that lets you scale authentication horizontally without a session store.</p><p>A typical OAuth 2.0 / OpenID Connect deployment issues three kinds of tokens. Access tokens authorize API calls. Refresh tokens are used only to obtain new access tokens. ID tokens carry information about who the user is, intended for the client application itself rather than for an API.</p><h3>Access Tokens</h3><p>An access token is the credential a client sends with every API request to prove it’s allowed to make that call. It’s the workhorse of the system. If you’re calling a protected endpoint, you’re sending an access token.</p><p>The defining property of an access token is that it should be short-lived. Typical lifetimes range from five minutes to one hour, with fifteen minutes being a common default. There is no rule here, only tradeoffs. The shorter the lifetime, the smaller the window an attacker has if they steal one, and the faster permission changes propagate. The longer the lifetime, the less load on the auth service from constant refreshes.</p><p>The reason access tokens are usually JWTs (and not opaque) is throughput. A microservices fleet might process tens of thousands of authenticated requests per second. Doing a database lookup on every one of them to validate a token is expensive. A JWT can be validated using only a public key and a few microseconds of CPU. That tradeoff (cheap validation in exchange for harder revocation) is the central design decision in modern auth.</p><h3>JWT Deep Dive</h3><p>A JWT is three base64url-encoded segments joined by dots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*QVzrH_V338KL93lYwQo1jA.png" /></figure><h4>Header</h4><p>The header identifies the signing algorithm and token type. It’s the smallest part of the token but it matters: an attacker who can manipulate the header can sometimes attack the signature scheme itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*JXDkMgrkv_otwKtl9hG7fw.png" /></figure><p>The kid (key ID) claim is what makes key rotation work. The auth service can sign with one key while still publishing the previous key for validation, and consumers know which key to use based on the kid in the header.</p><h4>Payload (Claims)</h4><p>The payload is a JSON object of claims. The IETF reserves a small set of standardized claim names; everything else is application-specific.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*0jN7XLf19D00uYp29AENKw.png" /></figure><p>The standardized claims serve specific functions. iss identifies the issuer, the auth service that minted the token. sub is the subject, almost always the user ID. aud declares the intended audience, the service or services that should accept this token. iat is when the token was issued. nbf (not before) is the earliest time the token is valid, useful for tokens that should be activated in the future. exp is the expiration timestamp. jti is a unique token identifier, useful for deduplication and for revocation lists.</p><p>The payload is not encrypted. Anyone who has the token can decode and read every claim. This is a frequent source of bugs: developers put information in a JWT that they thought was secret, then someone with the token reads it. If a claim needs to be private, the token needs to be encrypted (JWE), or the data should never be in the token at all.</p><h4>Signature</h4><p>The signature is computed over the header and payload using the algorithm declared in the header. The choice of algorithm splits into two families.</p><p>Symmetric algorithms (HS256, HS384, HS512) use the same secret to sign and verify. They’re fast but require every service that validates tokens to have access to the secret. If one service is compromised, the secret leaks and an attacker can forge tokens.</p><p>Asymmetric algorithms (RS256, RS384, ES256) use a private key to sign and a public key to verify. The auth service holds the private key; every other service only needs the public key. This is the standard choice for distributed systems because the blast radius of a compromised microservice doesn’t include the ability to forge tokens.</p><p>ES256 (ECDSA with P-256 and SHA-256) is increasingly preferred over RS256. Signatures are dramatically smaller (about 64 bytes versus 256 bytes for RSA-2048), keys are smaller, and operations are faster. RS256 remains common because of broader historical support.</p><h3>JWT Validation Flow</h3><p>The client sends the access token in the Authorization header:</p><pre>GET /api/orders/42 HTTP/1.1<br>Host: api.example.com<br>Authorization: Bearer eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI4ZjNlMmE5MSJ9.MEUCIQ...</pre><p>Validation has a fixed checklist. Skipping any step is a security bug.</p><p>First, parse the token structurally. Reject anything that isn’t three base64url segments separated by dots.</p><p>Second, verify the signature using the public key corresponding to the kid in the header. If the algorithm in the header isn&#39;t one your service has explicitly allowlisted, reject the token. This guards against algorithm confusion attacks where an attacker forges a token claiming alg: none or swaps RS256 for HS256.</p><p>Third, verify temporal claims. The current time must be greater than or equal to nbf (if present) and strictly less than exp. Apply a small clock skew tolerance (30 to 60 seconds is typical) to accommodate drift between servers.</p><p>Fourth, verify iss matches the expected issuer. A token from a different auth system, even if cryptographically valid against a different key, should be rejected.</p><p>Fifth, verify aud contains your service&#39;s identifier. Audience validation is the claim most often skipped, and it&#39;s the most dangerous one to skip in a multi-service environment. If service B accepts tokens minted for service A, then a compromised service A can pivot into service B.</p><p>Only after all five checks pass should the service treat the request as authenticated and proceed to authorization.</p><h3>Why Access Tokens Expire</h3><p>If access tokens never expired, the security model would collapse the first time one leaked. And tokens do leak. They leak through proxy logs, browser extensions, error reporting tools, cached request inspection panels, accidentally committed code, and exfiltration via XSS.</p><p>Short expiration limits the blast radius. A token stolen at 10:00 AM with a 15-minute lifetime stops working at 10:15. The attacker either has to pivot quickly or find a way to steal the refresh token too, which is harder because the refresh token is sent over the wire much less often.</p><p>There’s a second, less obvious reason. Authorization state changes. A user gets demoted, a role gets revoked, a contractor’s account gets disabled. Because JWTs are usually validated without a database lookup, the server has no way to know the user’s permissions changed until the token expires and the next access token reflects the new state. The shorter the access token lifetime, the faster permission changes propagate. A 15-minute access token means at most 15 minutes of authorization staleness, which is acceptable for most applications. A 24-hour access token means a fired employee can keep using their access for a day.</p><p>This is the principle of least privilege applied across time. Don’t grant more access than necessary, and don’t grant it for longer than necessary.</p><h3>Refresh Tokens</h3><p>A refresh token is a credential whose only purpose is to obtain new access tokens. It’s the second half of the token pair.</p><p>The defining characteristics of a refresh token are inverted from those of an access token. It’s long-lived, often 30 to 90 days, sometimes longer for “remember me” scenarios. It’s never sent to API services; it goes only to a single endpoint on the auth service. It’s typically stored more carefully than an access token, because compromising it gives an attacker a renewable source of access tokens.</p><p>The asymmetry is the whole point. Access tokens are widely exposed (every API call sends them) but only briefly valid. Refresh tokens are narrowly exposed (only refresh requests carry them) but valid for a long time. Together they cover both axes of the threat model.</p><h3>Why Refresh Tokens Exist</h3><p>The naive question is: why not just use long-lived access tokens? The answer becomes clear when you think through what each request actually does.</p><p>Every access token leaves traces in many places. CDN logs, application server logs, request tracing systems, browser network panels, error reporting payloads, mobile crash reports. A token that travels everywhere is a token that ends up in places it shouldn’t be. Making it short-lived means those traces stop being useful to an attacker within minutes.</p><p>But short-lived access tokens alone produce a terrible user experience. If users had to log in every 15 minutes, applications would be unusable. Refresh tokens solve the UX problem without compromising the security model. The refresh token sits in protected storage and only emerges to mint a new access token, then goes back into hiding.</p><p>You can think of the pair as a hot wallet and a cold wallet. The access token is hot: spent constantly, replaced when stolen. The refresh token is cold: only touched occasionally, kept in a safer place, and worth the trouble of locking down because losing it means losing the whole session.</p><h3>Authentication Lifecycle</h3><h4>Login</h4><p>The user authenticates once, usually with a password plus a second factor. The auth service verifies credentials and issues two tokens.</p><pre>POST /auth/login<br>Content-Type: application/json<br><br>{ &quot;email&quot;: &quot;u@example.com&quot;, &quot;password&quot;: &quot;...&quot;, &quot;totp&quot;: &quot;294817&quot; }<br><br>HTTP/1.1 200 OK<br>Content-Type: application/json<br><br>{<br>  &quot;access_token&quot;: &quot;eyJ...&quot;,<br>  &quot;token_type&quot;: &quot;Bearer&quot;,<br>  &quot;expires_in&quot;: 900,<br>  &quot;refresh_token&quot;: &quot;rt_8f3e2a91b4c7d6e5...&quot;,<br>  &quot;scope&quot;: &quot;openid profile email&quot;<br>}</pre><p>The access token expires in 900 seconds (15 minutes). The refresh token has its own expiration tracked server-side.</p><h4>API requests</h4><p>The client sends the access token with every API call. The refresh token never leaves storage during normal API use.</p><pre>GET /api/me HTTP/1.1<br>Host: api.example.com<br>Authorization: Bearer eyJ...</pre><p>The API service validates the JWT locally and proceeds. No round trip to the auth service. This is the property that makes the architecture scalable.</p><h4>Refresh</h4><p>When the access token expires (or is about to), the client sends the refresh token to the auth service&#39;s refresh endpoint.</p><pre>POST /auth/refresh<br>Content-Type: application/json<br><br>{ &quot;refresh_token&quot;: &quot;rt_8f3e2a91b4c7d6e5...&quot; }<br><br>HTTP/1.1 200 OK<br>Content-Type: application/json<br><br>{<br>  &quot;access_token&quot;: &quot;eyJ...&quot;,<br>  &quot;expires_in&quot;: 900,<br>  &quot;refresh_token&quot;: &quot;rt_9c8d7e6f5a4b3c2d...&quot;<br>}</pre><p>In a rotation scheme (covered below), the response contains both a new access token and a new refresh token. The old refresh token is invalidated.</p><h4>Logout</h4><p>Logout deletes the refresh token from server-side storage. The access token typically isn&#39;t revoked; it just expires naturally within minutes.</p><pre>POST /auth/logout<br>Authorization: Bearer eyJ...<br>Content-Type: application/json<br><br>{ &quot;refresh_token&quot;: &quot;rt_...&quot; }<br><br>HTTP/1.1 204 No Content</pre><p>This is one of the cleaner asymmetries of the design. You don&#39;t need a revocation list for access tokens because they have a short fuse. You only need to make sure no new access tokens get issued, which means killing the refresh token.</p><h3>Refresh Token Storage</h3><p>Where the refresh token lives on the client is one of the highest-stakes decisions in the system.</p><h4>Browser storage options</h4><p>Browsers offer three locations, each with distinct security properties.</p><p>localStorage is accessible to any JavaScript running on the page. This means any successful XSS attack reads the refresh token and exfiltrates it. The convenience of localStorage (any code can read it) is exactly the property that makes it dangerous.</p><p>sessionStorage has the same vulnerability profile as localStorage, with the additional downside that the token is lost on tab close. This makes it useful only for very short-lived sessions.</p><p>HttpOnly cookies are not accessible to JavaScript. An XSS attack cannot read the cookie value. The cookie is automatically sent on every request to the matching domain, which is convenient but also creates CSRF exposure. The standard mitigation is to combine the HttpOnly flag with the SameSite attribute (SameSite=Strict or SameSite=Lax) and the Secure flag (cookie only sent over HTTPS).</p><p>The practical recommendation for most web applications is HttpOnly + SameSite + Secure cookies for refresh tokens, with the refresh endpoint scoped to a path that no other request touches. This minimizes both XSS exposure (cookie is invisible to JS) and CSRF exposure (SameSite limits cross-origin sends).</p><h4>Mobile storage options</h4><p>Mobile platforms provide hardware-backed secure storage that’s substantially more secure than anything available in browsers.</p><p>On iOS, the Keychain stores credentials behind the device’s secure enclave. Access can be gated on biometric authentication, requiring the user to authenticate before the refresh token is even readable.</p><p>On Android, the Keystore performs the same role. Modern devices back keystore-protected keys with hardware (Trusted Execution Environment or StrongBox), so even root access on the device doesn’t directly expose the key material.</p><p>The mobile threat model is different from the browser one. The dominant browser threat is XSS. The dominant mobile threat is device theft. Hardware-backed storage with biometric unlock addresses both.</p><h4>Server-side storage</h4><p>The server should never store refresh tokens in plaintext. They’re credentials. The same reasoning that says you should hash passwords applies here: if the database leaks, the stored tokens should not be directly usable by an attacker.</p><p>A SHA-256 hash is sufficient. Refresh tokens are random high-entropy strings, so they don’t need the slow, salted hashes (bcrypt, Argon2) that user passwords need to defend against brute-force attacks. The hash protects against database dumps; that’s the whole job.</p><p>When a refresh request comes in, hash the incoming token and look up by hash. Never store the raw value.</p><h3>Refresh Token Database Design</h3><p>A workable schema captures who the token belongs to, what device it’s on, when it was issued, when it expires, whether it’s been used or revoked, and what token replaced it (for rotation tracking).</p><pre>CREATE TABLE refresh_tokens (<br>    id              UUID PRIMARY KEY,<br>    user_id         UUID NOT NULL REFERENCES users(id),<br>    token_hash      VARCHAR(64) NOT NULL UNIQUE,<br>    family_id       UUID NOT NULL,<br>    device_id       VARCHAR(255),<br>    device_name     VARCHAR(255),<br>    user_agent      TEXT,<br>    ip_address      INET,<br>    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),<br>    expires_at      TIMESTAMPTZ NOT NULL,<br>    last_used_at    TIMESTAMPTZ,<br>    revoked_at      TIMESTAMPTZ,<br>    revoked_reason  VARCHAR(50),<br>    replaced_by     UUID REFERENCES refresh_tokens(id)<br>);<br><br>CREATE INDEX idx_refresh_tokens_user ON refresh_tokens(user_id) WHERE revoked_at IS NULL;<br>CREATE INDEX idx_refresh_tokens_family ON refresh_tokens(family_id);<br>CREATE INDEX idx_refresh_tokens_expires ON refresh_tokens(expires_at) WHERE revoked_at IS NULL;</pre><p>Each column has a job. user_id is the obvious link to the user. token_hash is what you look up by; the raw token is never stored. family_id ties together every token in a rotation chain (more on this in the next section). device_id and device_name make &quot;log out from all devices&quot; usable and let users see active sessions in account settings. user_agent and ip_address support audit trails and anomaly detection. created_at and expires_at track lifetime. last_used_at supports inactivity-based expiration. revoked_at and revoked_reason track why a token died, which matters for debugging and security investigation. replaced_by lets you trace a rotation chain forward.</p><p>The partial indexes are not cosmetic. A production refresh token table tends to be heavily skewed toward revoked rows over time, and indexes that include revoked rows degrade quickly. Filtering on revoked_at IS NULL keeps the hot path fast.</p><h3>Refresh Token Rotation</h3><p>Rotation is the practice of issuing a new refresh token every time an old one is used, and immediately invalidating the old one. Each refresh request both renews the access token and replaces the refresh token.</p><p>Without rotation, a refresh token works for its full lifetime. If it’s stolen, the attacker has 30 to 90 days of guaranteed access until it expires naturally. With rotation, every successful refresh produces a new token; the previous one can never be used again. The window shrinks dramatically.</p><p>Conceptually, a token family is a chain: the user logs in and receives token A. They use A to refresh, getting B. They use B to refresh, getting C. Each new token’s family_id points back to the original. If any token in the chain is used after it has been replaced, the system has evidence that something is wrong.</p><p>The transaction matters. The new token must be created and the old one revoked atomically, or a crash between the two steps will lock the user out (or give them two valid tokens, depending on which happens first).</p><h3>Refresh Token Reuse Detection</h3><p>Reuse detection is what makes rotation worth the complexity. It’s how you find out a token was stolen.</p><p>The scenario: an attacker steals refresh token A from the user’s device. The legitimate user, unaware of the theft, uses A first. A is rotated into B. Now both the attacker and the legitimate user have references the attacker still holds A. When the attacker tries to use A, the server sees that A has already been revoked and replaced.</p><p>This is unambiguous evidence of theft. There is no benign explanation for using a token that’s already been rotated. The correct response is to revoke every token in the same family. Both the attacker and the legitimate user lose access. The legitimate user has to log in again. This is the right outcome: we don’t know which party is which, and locking everyone out and forcing fresh authentication is the only safe choice.</p><p>The reverse scenario also gets caught. The attacker uses A first and rotates it into B. The legitimate user later tries A. Same detection, same response.</p><p>There is one annoying false positive. Network failures can leave a client uncertain whether a refresh succeeded. The client retries with the old token. The server sees an old, revoked token and triggers reuse detection. To avoid this, clients should treat refresh as carefully as a financial transaction: serialize concurrent refreshes, persist the new token before discarding the old, and only retry after explicit confirmation of failure. Some implementations also grant a brief grace period where the immediately-previous token is treated as if it were the current one, which trades a small security window for fewer false positives.</p><h3>Access Token Revocation Problem</h3><p>JWTs are stateless by design. The server validates them without consulting any database. This is what makes them fast and scalable. It’s also what makes them hard to revoke.</p><p>If a user is fired, their permissions change, or their account is compromised, you’d like to invalidate their current access token immediately. But the API services validating those tokens have no idea anything has changed. They check the signature, check the expiration, check the audience, and let the request through. Until the access token expires naturally, the user keeps having access.</p><p>This is the fundamental tradeoff. Stateless validation gives you O(1) verification with no database hops. The cost is that you can’t yank a valid token mid-flight. Most production systems accept this tradeoff and compensate by keeping access tokens short.</p><h3>JWT Blacklists / Denylists</h3><p>The naive solution is to keep a list of revoked token IDs and check the list on every request. The list is keyed by jti (the unique token ID claim in the JWT) and lives in a fast store like Redis.</p><pre>def validate_access_token(jwt: str) -&gt; Claims:<br>    claims = verify_signature_and_claims(jwt)<br><br>    if redis.exists(f&quot;jwt_revoked:{claims[&#39;jti&#39;]}&quot;):<br>        raise RevokedToken()<br><br>    return claims</pre><p>When you need to revoke, you write the jti into Redis with an expiration equal to the token&#39;s remaining lifetime:</p><pre>def revoke_token(jti: str, exp: int) -&gt; None:<br>    ttl = exp - int(time.time())<br>    if ttl &gt; 0:<br>        redis.setex(f&quot;jwt_revoked:{jti}&quot;, ttl, &quot;1&quot;)</pre><p>This works. Revocation becomes immediate. But you’ve reintroduced the very thing JWTs were supposed to eliminate: a database lookup on every authenticated request. At scale, this is a significant cost. You’re now back to the same operational profile as opaque tokens (Redis on the hot path), with the additional complexity of JWT signing and validation on top.</p><h3>Why Most Systems Avoid JWT Blacklists</h3><p>The dominant production pattern is to skip blacklists entirely and keep access tokens short. A 15-minute access token bounds the worst-case window of unauthorized access at 15 minutes. For most use cases, that’s acceptable.</p><p>The alternative is to use blacklists only for sensitive scenarios: password changes, explicit “log out everywhere”, suspected account compromise. The blacklist exists but it’s small and rarely consulted. Most requests still validate purely against the signature.</p><p>Some systems split the difference: validate the signature on every request (cheap) and check a small bloom filter or local cache of recently revoked tokens (also cheap). The cache is kept in sync via pub/sub from the auth service. Falses positives in the bloom filter trigger a Redis check; false positives are rare, so the hot path stays fast.</p><p>The right answer depends on the application. Banking and healthcare often justify the blacklist cost. Most consumer applications don’t. The interview-style answer is: short access tokens are usually sufficient, and revocation goes through the refresh token, not the access token.</p><h3>OAuth 2.0 Context</h3><p>OAuth 2.0 is the framework that gave us the modern access/refresh token vocabulary. It’s worth knowing the roles even if you never implement an OAuth server yourself.</p><p>The Resource Owner is the human user. The Client is the application requesting access on their behalf (a mobile app, a web app, a third-party service). The Authorization Server issues tokens. The Resource Server hosts the protected APIs and validates the tokens.</p><p>In a simple deployment all three server roles can be a single service. In larger systems they’re separate. The OAuth specification was designed for the third-party delegation case (when you sign into a site using your Google account), but the same patterns apply equally well to first-party authentication (when an application authenticates its own users).</p><h4>Authorization Code Flow</h4><p>The Authorization Code flow is the standard pattern for browser-based and mobile clients. The high-level sequence:</p><p>The user clicks “sign in”. The application redirects them to the authorization server with the application’s client ID and a redirect URI. The user authenticates at the authorization server. The authorization server redirects the user back to the application’s redirect URI, carrying a short-lived authorization code in the URL. The application sends the authorization code to the authorization server from its backend, along with its client secret. The authorization server returns access and refresh tokens.</p><p>The reason for the indirection (code first, then exchange) is that the redirect URL passes through the user’s browser, where it’s exposed in browser history, referrer headers, and so on. The authorization code is single-use and short-lived (typically 60 seconds), so its exposure isn’t damaging. The actual tokens are exchanged server-to-server, never touching the browser.</p><h4>PKCE</h4><p>PKCE (Proof Key for Code Exchange) is what makes the Authorization Code flow safe for clients that can’t keep a client secret, primarily mobile and single-page applications.</p><p>The client generates a random secret called the code_verifier and a derived code_challenge:</p><pre>code_verifier = secrets.token_urlsafe(64)<br>code_challenge = base64url(https://medium.com/sha256(code_verifier.encode(&quot;ascii&quot;))).rstrip(&quot;=&quot;)</pre><p>The client sends the code_challenge (not the verifier) in the initial authorization request. When it later exchanges the authorization code for tokens, it sends the code_verifier. The authorization server hashes the verifier and checks that it matches the original challenge. An attacker who intercepts the authorization code can&#39;t redeem it without the verifier, which never crossed the network in plaintext.</p><p>PKCE is now required for all OAuth 2.0 public clients per the latest IETF guidance (OAuth 2.0 Security Best Current Practice). It&#39;s no longer optional.</p><h3>OpenID Connect</h3><p>OAuth 2.0 is fundamentally an authorization framework. It tells you what a client is allowed to do; it doesn&#39;t tell you who the user is. People used OAuth for authentication anyway by abusing the access token, treating successful API calls as proof of identity, which is a famously bad idea.</p><p>OpenID Connect is a thin layer on top of OAuth 2.0 that adds proper authentication. It introduces a third token type: the ID Token.</p><p>An ID Token is a JWT that contains user identity information. Unlike access tokens, ID tokens are intended for the client application, not for an API. The application reads the ID token to find out who just logged in.</p><h3>Conclusion</h3><p>The two-token model is what most production systems converge on for good reasons. Access tokens give you cheap, stateless authorization checks that scale to whatever request volume you can throw at them. Refresh tokens give you the long sessions users expect, with proper revocation and theft detection. Together they hit the three axes that matter: security (short exposure window for the credential that travels), scalability (no database on the hot path), and user experience (no constant logins).</p><p>The decisions that actually matter are smaller than they look. Pick short access token lifetimes. Use asymmetric signing with proper key rotation. Rotate refresh tokens and detect reuse. Hash refresh tokens server-side. Validate every claim on every request. Pick storage on the client that matches the platform’s threat model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=623ec5043d10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Terminal: The Anatomy of an Agentic Loop (Claude Code)]]></title>
            <link>https://medium.com/@van13heisenberg/behind-the-terminal-the-anatomy-of-an-agentic-loop-claude-code-8a5a00ee823f?source=rss-3852c29fa600------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a5a00ee823f</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-coding]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Aditya Vandan Sharma]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 13:48:56 GMT</pubDate>
            <atom:updated>2026-04-02T13:50:40.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dz3x-jBJ0xSOqamm.jpg" /></figure><blockquote><em>When you type a command into a coding agent, you aren’t just sending text to a model — you are triggering a high-precision recursive engine designed to bridge the gap between natural language and filesystem execution.</em></blockquote><p>The lifecycle of a single interaction within Claude Code follows a strictly orchestrated 11-step sequence that transforms a simple prompt into an autonomous series of actions. Most engineers interact with these systems daily without understanding the machinery underneath. This is that machinery.</p><h3>Phase 1</h3><h4>The Handshake</h4><p>The initial phase converts human intent into a structured format the machine can parse. What looks like a simple text prompt becomes a precisely shaped object before it ever touches the model.</p><h4>1. Input capture</h4><p>The cycle begins when a user submits a message via the terminal, or pipes data through stdin. Both paths converge at the same normalization step.</p><h4>2. Message normalization</h4><p>The createUserMessage() function encapsulates input into a formal JSON structure. A typical payload looks like this:</p><p>Example payload</p><pre>{<br>  &quot;role&quot;: &quot;user&quot;,<br>  &quot;content&quot;: [<br>    {<br>      &quot;type&quot;: &quot;text&quot;,<br>      &quot;text&quot;:  &quot;Search for TODOs&quot;<br>    }<br>  ]<br>}</pre><h4>3. History management</h4><p>The message object is pushed into a local, in-memory conversation array. This maintains the full context of the current session and is what allows the model to refer back to earlier results.</p><h4>4. System prompt assembly</h4><p>Before any API call, the system compiles a massive context block — combining CLAUDE.md instructions, all available tool definitions, local environment context, and active memory. This is the most expensive step per request and determines how &quot;aware&quot; the model feels.</p><h3>Phase 2</h3><h4>Live inference and tool detection</h4><p>Once context is assembled, the system engages the remote model. This is where the real-time feel of a coding agent comes from — and where the loop’s recursive character begins.</p><h4>5. Streaming API call</h4><p>The system opens a stream to the Anthropic API via Server-Sent Events. The model responds incrementally — tokens arrive as they are generated, not as a single payload at completion.</p><h4>6. Token parsing</h4><p>Tokens render live in the terminal as they arrive. The goal here is purely perceptual — minimizing the gap between model output and user visibility, even if the underlying computation takes time.</p><h4>7. Tool identification</h4><p>The parser watches specifically for tool_use blocks in the stream. When one appears, the system runs a lookup through findToolByName(), checks permissions via canUseTool(), and prepares the execution context.</p><h4>8. The recursive loop</h4><p>This is the architectural heart of the agent. The tool runs, output is captured, and results are appended back into the conversation history. The system then automatically restarts the API stream from step 5 — letting the model evaluate its own work and decide what to do next.</p><blockquote><em>“The tool runs, the output is captured, and the results are appended back to the history. The system then automatically restarts the API stream — letting the model evaluate its own work.”</em></blockquote><h3>Phase 2</h3><h4>Finalization and maintenance</h4><p>After the model determines the task is complete, the loop enters a cleanup and optimization stage. Most of this happens invisibly — but it’s what makes the agent feel coherent across long sessions.</p><h4>9. Rich rendering</h4><p>Final output is rendered in the terminal using Markdown — syntax highlighting for code blocks, formatting for tables, and clean prose rendering for everything else.</p><h4>10. Post-sampling hooks</h4><p>The agent performs three background tasks: <strong>context compaction</strong> (trimming history to fit the context window), <strong>memory extraction</strong> (saving key insights to persistent storage), and <strong>dream mode</strong> (running background optimizations for future tasks).</p><h4>11. REPL await</h4><p>The loop resets and enters a wait state, ready for the next user input. The cycle repeats from step 1.</p><blockquote><em>The next time you type a command and watch the terminal respond in real time, you now know what’s running underneath — a recursive loop that keeps calling itself until the model has nothing left to say.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a5a00ee823f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching and Caching Invalidation, the Complete Loop; Part 3]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@van13heisenberg/caching-and-caching-invalidation-the-complete-loop-part-3-8375f964c077?source=rss-3852c29fa600------2"><img src="https://cdn-images-1.medium.com/max/2350/1*GS3Ita62BMOrG1fI6GztTg.png" width="2350"></a></p><p class="medium-feed-snippet">Part 3: The Complete Loop &#x2014; &#x201C;Where It All Comes Together&#x201D;</p><p class="medium-feed-link"><a href="https://medium.com/@van13heisenberg/caching-and-caching-invalidation-the-complete-loop-part-3-8375f964c077?source=rss-3852c29fa600------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@van13heisenberg/caching-and-caching-invalidation-the-complete-loop-part-3-8375f964c077?source=rss-3852c29fa600------2</link>
            <guid isPermaLink="false">https://medium.com/p/8375f964c077</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Aditya Vandan Sharma]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 13:06:33 GMT</pubDate>
            <atom:updated>2026-03-22T13:06:33.361Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Caching and Caching Invalidation, the Complete Loop; Part 2]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@van13heisenberg/caching-and-caching-invalidation-the-complete-loop-part-2-6183fac77a9d?source=rss-3852c29fa600------2"><img src="https://cdn-images-1.medium.com/max/1844/1*5Dit70RutYhxi1ddlhktnA.png" width="1844"></a></p><p class="medium-feed-snippet">Part 2: Cache Invalidation &#x2014; &#x201C;The Two Hard Things in Computer Science&#x201D;</p><p class="medium-feed-link"><a href="https://medium.com/@van13heisenberg/caching-and-caching-invalidation-the-complete-loop-part-2-6183fac77a9d?source=rss-3852c29fa600------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@van13heisenberg/caching-and-caching-invalidation-the-complete-loop-part-2-6183fac77a9d?source=rss-3852c29fa600------2</link>
            <guid isPermaLink="false">https://medium.com/p/6183fac77a9d</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Aditya Vandan Sharma]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 11:49:57 GMT</pubDate>
            <atom:updated>2026-03-22T13:08:26.479Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Caching and Caching Invalidation, the Complete Loop; Part 1]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@van13heisenberg/caching-and-caching-invalidation-the-complete-loop-part-1-29e9107ece48?source=rss-3852c29fa600------2"><img src="https://cdn-images-1.medium.com/max/1984/1*dK_nl5xKoXnaFOfahfPZaw.png" width="1984"></a></p><p class="medium-feed-snippet">Part 1: Caching Strategies &#x2014; &#x201C;How to Go Fast Without Breaking Things&#x201D;</p><p class="medium-feed-link"><a href="https://medium.com/@van13heisenberg/caching-and-caching-invalidation-the-complete-loop-part-1-29e9107ece48?source=rss-3852c29fa600------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@van13heisenberg/caching-and-caching-invalidation-the-complete-loop-part-1-29e9107ece48?source=rss-3852c29fa600------2</link>
            <guid isPermaLink="false">https://medium.com/p/29e9107ece48</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Aditya Vandan Sharma]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 11:36:45 GMT</pubDate>
            <atom:updated>2026-03-22T13:07:37.583Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Compression in Web APIs: A Practical Guide]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@van13heisenberg/compression-in-web-apis-a-practical-guide-28eefa778ea9?source=rss-3852c29fa600------2"><img src="https://cdn-images-1.medium.com/max/2600/1*smBZzGvsJqfJgyRf0PsEVg.png" width="2968"></a></p><p class="medium-feed-snippet">Overview</p><p class="medium-feed-link"><a href="https://medium.com/@van13heisenberg/compression-in-web-apis-a-practical-guide-28eefa778ea9?source=rss-3852c29fa600------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@van13heisenberg/compression-in-web-apis-a-practical-guide-28eefa778ea9?source=rss-3852c29fa600------2</link>
            <guid isPermaLink="false">https://medium.com/p/28eefa778ea9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Aditya Vandan Sharma]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 16:27:15 GMT</pubDate>
            <atom:updated>2026-02-08T16:27:15.119Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Design Patterns, A deep dive Part 2 (Structural Design Patterns)]]></title>
            <link>https://tech.groww.in/design-patterns-a-deep-dive-part-2-structural-design-patterns-b2ff1487393?source=rss-3852c29fa600------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2ff1487393</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[structural-design-pattern]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aditya Vandan Sharma]]></dc:creator>
            <pubDate>Sun, 13 Jun 2021 16:31:05 GMT</pubDate>
            <atom:updated>2021-06-15T04:16:54.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*61w118UleZZfq2sbtXC8SQ.jpeg" /></figure><p>We have covered what are <strong>Design Patterns</strong> and all <strong>Creational Design Patterns </strong>in part 1 of this article series which you can check out <a href="https://tech.groww.in/design-patterns-a-deep-dive-part-1-c3d4e7c290cf">here</a>.</p><p>What are Structural Design Patterns?. We have already discussed in part 1 that Structural design patterns help in defining control over the object’s structure and working. So let’s look at the different patterns out there.</p><h3>1. Bridge Pattern</h3><p>The Bridge pattern allows two components, a client and a service, to work together with each component having its own interface. A bridge is a high-level architectural pattern and its main goal is to write better code through two levels of abstraction.<br>In this pattern, the classes and their implementation change often and therefore, they are loosely coupled with each other.<br>Please check the below implementation for better understanding:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6db8dc0c724c326394aab403635705c5/href">https://medium.com/media/6db8dc0c724c326394aab403635705c5/href</a></iframe><h3>2. Adaptor Pattern</h3><p>The adapter pattern is a structural design pattern that allows objects with incompatible interfaces to collaborate.<br>This pattern makes dissimilar classes work. It makes a medium between 2 dissimilar classes. E.g. a class object gives XML output and other class object takes a JSON input. Then, A mediator is required so that the 2 classes would work, and this mediator class is called the Adapter.<br>Here’s a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/560ca559d5e5108e467baaa6e2d6baf6/href">https://medium.com/media/560ca559d5e5108e467baaa6e2d6baf6/href</a></iframe><h3>3. Composite Pattern</h3><p>The composite pattern is used to structure objects in a tree-like hierarchy. Here, each node of the tree can be composed of child nodes and some implementation with data. <br>The Composite pattern provides you with two basic element types that share a common interface: simple leaves and complex containers.<br>You can checkout code example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d27e61257655da687226bae99c3063fd/href">https://medium.com/media/d27e61257655da687226bae99c3063fd/href</a></iframe><h3>4. Decorator Pattern</h3><p>A decorator<strong> </strong>pattern is a structural design pattern that lets you attach new behaviours to objects by placing these objects inside special wrapper objects that contain the behaviours.<br>In the decorator pattern, classes are wrapped inside other classes, where the wrapper class add functionalities to the wrapped class. And therefore this pattern extends the behaviour of an object dynamically.<br>Here’s an example</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80b084038dc73dc4547c610411f42f67/href">https://medium.com/media/80b084038dc73dc4547c610411f42f67/href</a></iframe><h3>5. Flyweight Pattern</h3><p>Flyweight pattern lets you fit more objects into the available amount of RAM by sharing common parts of the state between multiple objects instead of keeping all of the data in each object.<br>This pattern works on the principle that, Sharing state among a large amount of fine-grained object increases efficiency. A flyweight object can consist of two states:</p><ul><li><strong>intrinsic:</strong> this state is stored in the flyweight. It contains the information required by the internal methods of objects. It is independent of the context of the flyweight; hence, it is sharable with other objects.</li><li><strong>extrinsic:</strong> this state depends on the context of the flyweight; hence, it cannot be shared. Normally, the client objects pass the extrinsic state to the flyweight object when needed</li></ul><p>Check out this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ade4c071dc89ff5344a934c1d7e56fb6/href">https://medium.com/media/ade4c071dc89ff5344a934c1d7e56fb6/href</a></iframe><h3>6. Proxy Pattern</h3><p>the proxy pattern is a structural pattern that creates a proxy object. It acts as a placeholder for another object, controlling access to it. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.<br>In this pattern, there is a “Subject” object which has time/memory/resource expensive functionality. So for using /calling these functionalities, proxy objects are used.<br>Here’s a data service example, which explains the pattern.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/290c2d658eb2a2c0f54e1fca1f87effc/href">https://medium.com/media/290c2d658eb2a2c0f54e1fca1f87effc/href</a></iframe><p>And with that, we conclude the second part of the series. You can refer to the resources I mentioned in the first article to get a deeper insight. This series is mainly focused on explaining these design patterns with simple and self-explanatory examples. I hope you had fun while learning something new XD.</p><p>If you enjoyed this story, please click the 👏 button and share to help others find it! Feel free to leave a comment below.</p><p>The Groww Engineering publishes technical stuff, the latest technologies, and better ways to tackle common programming problems. You can subscribe to get them <a href="https://tech.groww.in/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2ff1487393" width="1" height="1" alt=""><hr><p><a href="https://tech.groww.in/design-patterns-a-deep-dive-part-2-structural-design-patterns-b2ff1487393">Design Patterns, A deep dive Part 2 (Structural Design Patterns)</a> was originally published in <a href="https://tech.groww.in/">The Groww Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns, A deep dive Part 1 (Creational Design Patterns)]]></title>
            <link>https://tech.groww.in/design-patterns-a-deep-dive-part-1-c3d4e7c290cf?source=rss-3852c29fa600------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3d4e7c290cf</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Aditya Vandan Sharma]]></dc:creator>
            <pubDate>Mon, 24 May 2021 00:22:43 GMT</pubDate>
            <atom:updated>2025-04-21T07:35:27.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0rSx2Gw0T8zFK0SwU9Yew.jpeg" /></figure><p>It’s been years since the software industry has been working on creating different complex structures of code to create amazing products and services while encountering a myriad of problems in creating and maintaining these structures. And during this whole journey, developers started recognising problems that can be solved in a specified defined fashion which is a coding <strong>design pattern.</strong></p><p>Most of the design patterns can be used irrespective of the programming language we are writing code in, although some design patterns are specifically designed for some languages for e.g. module pattern in javascript while some require object-oriented capabilities in the programming language. We are going to cover all generic design patterns using javascript with examples and some js specific patterns. So don’t worry.</p><p>This is going to be three-part article series for explaining all design pattern. So hang in there, bud. You are up for a long ride.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F2d98nRiVVB6HS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F2d98nRiVVB6HS%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F2d98nRiVVB6HS%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="253" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f0e6b8c010e506ed073bbc66051bba9/href">https://medium.com/media/2f0e6b8c010e506ed073bbc66051bba9/href</a></iframe><h3>What is a design pattern?</h3><p>In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. Design patterns can be classified into the following different categories on the basis of their level of detail, complexity, and scale of applicability to the entire system being design.</p><ol><li><strong>Creational Design Patterns</strong></li><li><strong>Structural Design Patterns</strong></li><li><strong>Behavioural Design Patterns</strong></li></ol><h3><strong>1. Creational Design Patterns</strong></h3><p>Creational patterns provide various object creation mechanisms, which increase flexibility and reusability of existing code. Basically, they help in defining the control over the object creation. These can be further classified into different types:</p><ol><li>Builder Pattern</li><li>Singleton Pattern</li><li>Prototype Pattern</li><li>Factory and Abstract Factory Pattern</li></ol><h3>2. Structural Design Patterns</h3><p>These patterns explain how to assemble objects and classes into larger structures while keeping these structures flexible and efficient. Or in other words, they help in defining control over the object’s structure and working. These can be further classified into different types:</p><ol><li>Bridge Pattern</li><li>Adaptor Pattern</li><li>Composite Pattern</li><li>Decorator Pattern</li><li>FlyWeight Pattern</li><li>Proxy Pattern</li></ol><h3>3. Behavioural Design Patterns</h3><p>These patterns are concerned with algorithms and the assignment of responsibilities between objects. In doing so, these patterns increase flexibility in carrying out communication between objects and classes. These can be further classified into different types:</p><ol><li>Interpreter Pattern</li><li>Template Pattern</li><li>Chain of Responsibility Pattern</li><li>Command Pattern</li><li>Iterator Pattern</li><li>Mediator Pattern</li><li>Memento Pattern</li><li>Observer Pattern</li><li>State Pattern</li><li>Strategy Pattern</li><li>Visitor Pattern</li></ol><p>Now That we have listed all the patterns we need to cover, let’s get on with diving deep and looking at some examples, I will try to make the code self-explanatory. XD</p><h3>Builder Pattern</h3><p>In this pattern, building an object might require a specific and complex procedure. Therefore, the Builder class is designed and delegated the task of object creation.<br>The simplest <strong>real-world example</strong> of the <strong>builder pattern </strong>is complex metal parts are required to be made, then mould (builders) that are used to create the part.<br>Let’s see a coding example</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6842e5c9f06ee74cfb8b4a9e691f44b7/href">https://medium.com/media/6842e5c9f06ee74cfb8b4a9e691f44b7/href</a></iframe><h3>Singleton Pattern:</h3><p><strong>Singleton</strong> is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.<br>The pattern is used for creating and ensuring a single instance of a class for the whole application. <br>(Hint: we make this possible by making the constructor private, But since we cannot create private members in js we can use js oriented pattern called the module pattern to achieve a proper singleton pattern, we will discuss more about this in module pattern)<br>A real world example would be a Demat account from a broker. It is created only once but then used everywhere by the broker.<br>Let’s checkout a coding example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6284d1b048fd9b832e35a19cea00d79a/href">https://medium.com/media/6284d1b048fd9b832e35a19cea00d79a/href</a></iframe><h3>Prototype Pattern:</h3><p>This pattern involves creating new objects by copying existing object without making the code dependent on the classes.. The object being copied is called the prototype.<br>A real world example would be of an amoeba reproducing by binary fission. The children are almost same as the parent but with some little difference.<br>Given is code example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e2f3a216f5a9b6913d7e5abab8ae6fb/href">https://medium.com/media/5e2f3a216f5a9b6913d7e5abab8ae6fb/href</a></iframe><h3>Factory and Abstract Factory Pattern:</h3><p>Abstract Factory<strong> </strong>is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.<br>Using “new” keyword to create new instances of a class tightly couples our code to concrete implementation. <br>Every implementation of this pattern requires a basic element called Factory which creates instances for us.<br>A real world example is an actual factory creating a family of products.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01bcfb8a2ed3df96c324d2042ef559ef/href">https://medium.com/media/01bcfb8a2ed3df96c324d2042ef559ef/href</a></iframe><p>So that concludes Creational Design Patterns. If you want to learn more checkout part 2 of this series in which we will cover Structural Design Patterns. here’s the <a href="https://tech.groww.in/design-patterns-a-deep-dive-part-2-structural-design-patterns-b2ff1487393">link</a>.</p><p>You can try out examples from this article <a href="https://github.com/AdityaVandan/design-pattern-examples/tree/main/examples">here</a></p><h3>Resources referred (which you can refer too XD):</h3><ul><li><a href="https://sourcemaking.com/">https://sourcemaking.com/</a></li><li><a href="https://refactoring.guru/">https://refactoring.guru/</a></li><li><a href="https://medium.com/educative/the-7-most-important-software-design-patterns-d60e546afb0e">https://medium.com/educative/the-7-most-important-software-design-patterns-d60e546afb0e</a></li><li><a href="https://www.freecodecamp.org/news/the-basic-design-patterns-all-developers-need-to-know/">https://www.freecodecamp.org/news/the-basic-design-patterns-all-developers-need-to-know/</a></li><li><a href="http://www.thedevpiece.com/design-patterns-that-every-developer-should-know/">http://www.thedevpiece.com/design-patterns-that-every-developer-should-know/</a></li><li><a href="http://www.celinio.net/techblog/?p=65">http://www.celinio.net/techblog/?p=65</a></li><li><a href="https://www.edureka.co/blog/java-design-patterns/">https://www.edureka.co/blog/java-design-patterns/</a></li><li><a href="https://addyosmani.com/resources/essentialjsdesignpatterns/book/">https://addyosmani.com/resources/essentialjsdesignpatterns/book/</a></li><li><a href="https://www.digitalocean.com/community/tutorial_series/javascript-design-patterns">https://www.digitalocean.com/community/tutorial_series/javascript-design-patterns</a></li><li><a href="https://www.toptal.com/javascript/comprehensive-guide-javascript-design-patterns">https://www.toptal.com/javascript/comprehensive-guide-javascript-design-patterns</a></li></ul><p>If you enjoyed this story, please click the 👏 button and share to help others find it! Feel free to leave a comment below.</p><p>Groww Engineering publishes technical pieces, the latest knick-knacks in the coding world, and convenient ways to tackle common programming problems.</p><p>Read more of our articles <a href="https://tech.groww.in/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3d4e7c290cf" width="1" height="1" alt=""><hr><p><a href="https://tech.groww.in/design-patterns-a-deep-dive-part-1-c3d4e7c290cf">Design Patterns, A deep dive Part 1 (Creational Design Patterns)</a> was originally published in <a href="https://tech.groww.in/">The Groww Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting data from DOM tree of a web page into a python dictionary]]></title>
            <link>https://medium.com/@van13heisenberg/extracting-data-from-dom-tree-of-a-web-page-into-a-python-dictionary-902a79ce0694?source=rss-3852c29fa600------2</link>
            <guid isPermaLink="false">https://medium.com/p/902a79ce0694</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[trees]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aditya Vandan Sharma]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 13:01:43 GMT</pubDate>
            <atom:updated>2020-08-30T13:01:43.288Z</atom:updated>
            <content:encoded><![CDATA[<p>Just a heads up, in this article we are going to use python, selenium and a little bit of JavaScript for extracting meta data of different elements in a web-page</p><p>Now if we are using these technologies and some other relevant concepts, that means we need introduction to some relevant jargon right!!<br>So here it begins:</p><p><strong>Document Object Model (DOM): <br></strong>The Document Object Model is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.<br>e.g.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*CcxghvAHaaaI-tOPkqP-og.png" /></figure><p>We are going to traverse this DOM, which as you already have guessed is a tree kind of structure, and copy this structure into a tree like DS of JSONs.<br>Now there must be a question which arrived in your mind, why is it we require to traverse DOM tree when web page (xml) is well structured enough on it’s own which we could easily parse using some web scraping library like beautiful soup?.<br>Well it’s because sometimes these web pages are constructed by browser while the page is rendered and therefore it’s xml structure is not present in a hard coded file. Also there is some other relevant info like CSS and coordinate properties of an element which can only be extracted with DOM using JavaScript.<br>And So, we are going to use selenium to extract the constructed DOM tree.</p><p><strong>Selenium: <br></strong>Selenium is a portable framework for testing web applications. Selenium provides a playback tool for authoring functional tests without the need to learn a test scripting language.<br>Selenium makes use of a browser driver to render web page, therefore we can also run some JavaScript over the page member attributes.</p><p>OK, I think this much context was enough!!. And I hope you are familiar with a bit of JS and python. Let’s move on to the coding part.</p><p>Firstly, let’s configure selenium chrome driver with python.<br>We need to download the latest stable version unzip it and provide relative path while configuration in the python script. In this article we are going to use<em> </em><a href="https://chromedriver.storage.googleapis.com/index.html?path=84.0.4147.30/"><em>ChromeDriver 84.0.4147.30</em></a><em> . </em>Please find other relevant versions <a href="https://chromedriver.chromium.org/home">here</a>.</p><p>Add chrome driver path(where you unzipped the chrome driver) to the driver path in driver_config class and js_script_path in js_code class which will extract the dom tree, in the given gist below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82ec2cc249e13a6af3058f369416faa6/href">https://medium.com/media/82ec2cc249e13a6af3058f369416faa6/href</a></iframe><p>We require some JavaScript code to extract the tree as JS can interact with the DOM. The following JS code does a dfs on the tree element and extracts the tree starting from the “body” parent element.(this is the file used in the js_code class)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fa8a075a8cceecb6a660d05124d16fe/href">https://medium.com/media/8fa8a075a8cceecb6a660d05124d16fe/href</a></iframe><p>Now let’s integrate all of this and extract a tree JSON for the DOM. By using the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c70946c4e50d37e8e415c6b7b0c4ba88/href">https://medium.com/media/c70946c4e50d37e8e415c6b7b0c4ba88/href</a></iframe><p>Add your test url in the above snippet in the test_url variable and the json would be written in a file called DOM.json<br>And Finally we get a “page_tree” variable which contains the whole page tree as a python dictionary.</p><p>Well, our objective is achieved and that concludes this article, hope you got some insights on extracting html elements from a web page. You can also checkout the whole code from this <a href="https://github.com/AdityaVandan/dom_tree_extractor">repositiory</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=902a79ce0694" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Tesseract with python]]></title>
            <link>https://medium.com/analytics-vidhya/using-tesseract-with-python-1cadbe37e756?source=rss-3852c29fa600------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cadbe37e756</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tesseract]]></category>
            <category><![CDATA[tesserocr]]></category>
            <category><![CDATA[pytesseract]]></category>
            <dc:creator><![CDATA[Aditya Vandan Sharma]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 23:43:02 GMT</pubDate>
            <atom:updated>2026-08-31T07:06:01.318Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*_2nsdmjpH6VsGp1imcJJqQ.png" /></figure><p>Tesseract-ocr is an optical character recognition engine for various operating systems. It is free software, released under the Apache License. And made open source in 2005 and has been sponsored by google since 2006.</p><p>This engine has it’s binaries, a CLI program and it’s original API is made in C++. Other programming languages have their own libraries which act as wrappers over the CLI program or original tesseract API on C++.</p><p>In this article, we are going to discuss about the different options out there for using tesseract with python (their installation, executing different API ends)and some important problems encountered during there usage.</p><blockquote>In python there are two most popular options: pytesseract and tesserocr.</blockquote><blockquote>tesserocr is a python wrapper around the Tesseract C++ API. On the other hand, pytesseract is a wrapper the tesseract-ocr CLI program.</blockquote><blockquote>And as you can guess tesserocr gives a lot more flexibility and control over tesseract. Tesserocr has multi-processing capabilities which are much faster in actual practise as compared to PyTesseract.</blockquote><p>According to your use case you might require legacy package 3.05 or the latest tesseract version 4+ . For example tesseract 4.0 doesn’t provide font information of the recognized texts and therefore you would require the older version to gather that information.</p><h4>Generic Setup:</h4><p>For trying the examples you need to install <a href="https://www.anaconda.com/products/individual">anaconda </a>for package and environment variable management.<br>Once installed, create a new environment with python installation which is required by the tesseract version being used (Note: for our examples use python 3.7)and activate the environment every time you run any example:</p><pre><strong>create environment:</strong> conda create -n tesseractEnvironment python=3.7<br><strong>activate environment: </strong>conda activate tesseractEnvironment</pre><h3>Tesseract</h3><p>For using any tesseract python wrapper we need to install tesseract-ocr first. To install tesseract on Debian/Ubuntu:</p><pre>sudo apt install tesseract-ocr<br>sudo apt install libtesseract-dev</pre><p><strong><em>Note:</em></strong><em> the above command lines would install the latest available version of tesseract-ocr i.e. tesseract 4. You have to manually compile tesseract repository if you want to use an earlier version like 3.05 which might be necessary if you want to extract font-related information of texts, If it is too complex for you to manually compile tesseract 3.05 then, we will discuss further on a work around solution to complete the setup.</em></p><p>For a windows installation checkout: <a href="https://github.com/UB-Mannheim/tesseract/wiki">https://github.com/UB-Mannheim/tesseract/wiki</a></p><p>Tesseract has various type of pretrained models having a trade off between speed and accuracy which are to be provided along with the tesseract-ocr path if to be used. These models include:<br>1. tessdata (for legacy tesseract i.e. 3.05) <br>2. tessdata_best (for latest version)<br>3. tessdata_fast (for latest version)<br>download the tessdata pretrained models according to your usecase. By default you don’t need to worry about the tessdata setup because default tessdata is available with tesseract-ocr<br>Refer: <a href="https://github.com/tesseract-ocr/tesseract-ocr.github.io">https://github.com/tesseract-ocr/tesseract-ocr.github.io</a> for more info</p><p>Now, We will look into some APIs of first PyTesseract and then Tesserocr<br>This article will cover topics in the following parts:<br>1. Setup<br>2. exposed API description<br>3. Code snippet example</p><h3>Pytesseract</h3><p><strong>Setup:<br></strong>for installing Pytesseract in your environment:</p><pre>conda install -c conda-forge pytesseract</pre><p>If tesseract is not in your path you would have to provide path to the installation using pytesseract.pytesseract.tesseract_cmd variable in your code.</p><h4>API Description</h4><p>pytesseract has the following popular apis exposed:<br>1. pytesseract.image_to_string(image) returns text recognized in the image<br>2. pytesseract.image_to_boxes(image) bounding boxes of each recognized word<br>3. pytesseract.image_to_data(image) data related to dimensions, line, paragraph info of a recognized word<br>4. pytesseract.image_to_osd(image) confidence and other page related info<br>5. pytesseract.image_to_pdf_or_hocr(image, extension=’pdf’ /’hocr’) pdf form of image or xml formatted information</p><h4>Code Snippet Example</h4><p>Run the following code snippet to get a good idea about the apis<br><em>Note: please provide path to the tesseract executable in the tesseract_cmd variable if the below snippet is not working.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/241a5b1879e65a516e45a9f72f131caa/href">https://medium.com/media/241a5b1879e65a516e45a9f72f131caa/href</a></iframe><h3>TesserOCR</h3><p>Install the latest stable version,but if you want to extract font info you need to use tesserocr v2.3.1 because that is compatible with tesseract3.05.</p><h4>Setup</h4><p>for installing tesserocr in your environment:</p><p>Debian/Ubuntu:</p><pre><strong>tesserocr latest:</strong> conda install -c conda-forge tesserocr<br><strong>tesserocr v2.3.1: </strong>conda install -c mcs07 tesserocr <br>or <a href="https://anaconda.org/mcs07/tesserocr/2.3.1/download/linux-64/tesserocr-2.3.1-py36h6bb024c_0.tar.bz2">https://anaconda.org/mcs07/tesserocr/2.3.1/download/linux-64/tesserocr-2.3.1-py36h6bb024c_0.tar.bz2</a></pre><p>Windows:</p><pre><strong>tesserocr latest:</strong> conda install -c simonflueckiger tesserocr<br><strong>tesserocr v2.3.1: </strong>conda install -c simonflueckiger/label/tesseract-3.5.2 tesserocr</pre><h4>API Description</h4><p>Tesserocr has the following useful apis:<br>1. tesserocr.image_to_text(image)<br>2. PyTessBaseAPI().GetUTF8Text()<br>3. PyTessBaseAPI().MeanTextConf()<br>4. PyTessBaseAPI().DetectOrientationScript()<br>The above apis are pretty straight forward and there examples could be easily understood via there <a href="https://github.com/sirfz/tesserocr"><em>documentation</em></a><em>.</em></p><p>The task what I want to focus on is how extract font data. You can get a pretty good idea by trying the following script.<br><em>Note: please provide the tessdata path being used in the path variable if you want to use some specific pretrained model.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5a40775c40e887a4411956bb4a2acba/href">https://medium.com/media/c5a40775c40e887a4411956bb4a2acba/href</a></iframe><p>To check all the tesseract c++ APIs exposed checkout: <a href="https://tesseract-ocr.github.io/">https://tesseract-ocr.github.io/</a> . These can be used with tesserocr as well.</p><h3>A .NET Note on the Same Trade-Off</h3><p>the pytesseract-as-CLI-wrapper versus tesserocr-as-C++-API-binding distinction is the part most Tesseract tutorials skip entirely, and it’s exactly why the two behave so differently under load.</p><p>Worth adding a note for anyone hitting this from the .NET side, since the same trade-off exists there but resolves differently.</p><p><strong>IronOCR</strong> binds to the Tesseract C++ API directly rather than shelling out to the CLI — so it sits on the tesserocr side of your comparison, with the multiprocessing behaviour that implies. The practical difference is the setup: no <strong><em>apt install tesseract-ocr libtesseract-dev</em></strong>, no conda channel juggling, and no tessdata path to configure. The engine and language data ship inside the NuGet package.</p><pre>PM &gt; Install-Package IronOcr</pre><pre>using IronOcr;<br><br>var ocr = new IronTesseract();<br>using var input = new OcrInput();<br>input.LoadImage(&quot;image.png&quot;);<br><br>var result = ocr.Read(input);<br>Console.WriteLine(result.Text);</pre><p>Mapping onto the APIs you list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*afz-Og_nNtGFlE4l70Ndhg.png" /></figure><p>The structured results come back as objects rather than parallel arrays, so there’s no indexing <strong>data[‘left’][i]</strong> against <strong>data[‘text’][i]</strong> to reassemble a word with its box.</p><p><strong>On tessdata point: </strong>the tessdata / tessdata_best / tessdata_fast trade-off applies here too, and IronOCR ships language packs as separate NuGet packages (<strong>IronOcr.Languages.*</strong>), which sidesteps the “download the right model and set the path” step that trips people up in the setup section.</p><p><strong>One honest caveat on font-information note:</strong> that’s a genuine Tesseract 3.05-only capability, and IronOCR is built on Tesseract 5 — so it shares the same limitation. If font metadata is the requirement, the tesserocr 2.3.1 + Tesseract 3.05 pinning you describe remains the only route, awkward as it is.</p><p>.NET only, so this isn’t a swap for a Python project — relevant if that side of a pipeline is C#.<a href="https://ironsoftware.com/csharp/ocr/"> IronOCR for .NET</a> · free 30-day trial.</p><p>Well we reached end of this session. Hope you enjoyed and found this article useful!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cadbe37e756" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/using-tesseract-with-python-1cadbe37e756">Using Tesseract with python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>