<?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 Jack Pritom Soren on Medium]]></title>
        <description><![CDATA[Stories by Jack Pritom Soren on Medium]]></description>
        <link>https://medium.com/@jackpritomsoren?source=rss-17ac2beef113------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MEAt5stmDTwkvBKy8WNu6Q.jpeg</url>
            <title>Stories by Jack Pritom Soren on Medium</title>
            <link>https://medium.com/@jackpritomsoren?source=rss-17ac2beef113------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 03:37:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jackpritomsoren/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[HTTP Interceptors: The Complete Guide to Request & Response Handling in React and Angular]]></title>
            <link>https://medium.com/@jackpritomsoren/http-interceptors-the-complete-guide-to-request-response-handling-in-react-and-angular-d515521e0832?source=rss-17ac2beef113------2</link>
            <guid isPermaLink="false">https://medium.com/p/d515521e0832</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jack Pritom Soren]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 06:52:20 GMT</pubDate>
            <atom:updated>2026-09-11T06:52:20.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSNQ1U8lQqcZX8h2Riqf8w.jpeg" /></figure><h3>Introduction: The Problem Before Interceptors</h3><p>Imagine you’re building a real-world application. Your API calls need authentication headers on every single request. Your error responses need to refresh expired tokens. Failed requests should retry. Loading states should show spinners. Response times should be logged for debugging. And oh, some requests need to cache their results to avoid hammering the server.</p><p>Now imagine doing <em>all of that</em> inside every component that makes an API call. You’d be copy-pasting the same validation, error-handling, and auth logic across fifty different fetch statements. Your codebase becomes a nightmare of repetition. Bugs multiply. Maintenance becomes a horror show.</p><p>This is why <strong>HTTP interceptors</strong> exist. They’re middleware for your HTTP layer — a central place where you can inspect, modify, and handle every request and response flowing through your application. Once you set them up, every API call automatically benefits from your authentication logic, error handling, retry policies, and logging without a single line of duplicate code.</p><p>This guide will take you from “what even is an interceptor?” through production-grade implementations in both React and Angular. We’ll build real examples, hit the edge cases, and show you how to think about interceptor architecture so you’re not wrestling with them six months from now.</p><h3>What We’ll Cover</h3><ol><li><strong>Core Concepts</strong> — What interceptors actually are and why you need them</li><li><strong>The Mental Model</strong> — How to think about request and response flow</li><li><strong>React + Axios</strong> — Setting up interceptors in React with working examples</li><li><strong>React in Production</strong> — Token refresh, 401 handling, and common mistakes</li><li><strong>Angular Interceptors</strong> — The functional approach and architectural patterns</li><li><strong>Angular in Production</strong> — Multiple interceptors, ordering, and complex scenarios</li><li><strong>React vs Angular</strong> — Direct comparison and when to use each approach</li><li><strong>Limitations &amp; Production Architecture</strong> — What interceptors <em>can’t</em> do and how to handle it</li></ol><h3>Part 1: Core Concepts</h3><h3>What Is an HTTP Interceptor?</h3><p>An HTTP interceptor is a function (or class, depending on the framework) that sits between your application and the network. Every HTTP request passes through it <em>before</em> hitting the server. Every response passes through it <em>after</em> leaving the server. You can intercept at either or both stages.</p><p>Think of it like a mail sorter at a post office:</p><ul><li><strong>Request interceptor</strong> = the sorter checks outgoing mail, adds postage and routing info, maybe redirects some packages</li><li><strong>Response interceptor</strong> = the sorter receives incoming mail, verifies stamps, opens unopened packages, and sorts them by recipient</li></ul><p>The key idea: <strong>you intercept, you inspect, you can modify, then you pass it along</strong> (or stop it entirely if something’s wrong).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*a6HGu4tLrhqUE_iD.png" /></figure><h3>Why Do We Need Interceptors?</h3><p>Without interceptors, you’d handle every cross-cutting concern (auth, errors, logging) inside every component. With interceptors, you handle it once, globally.</p><p><strong>Real-world scenarios interceptors solve:</strong></p><ul><li><strong>Authentication</strong> — Add JWT tokens to every request without thinking about it</li><li><strong>Error handling</strong> — Catch 401s globally, refresh the token, retry the request automatically</li><li><strong>Loading states</strong> — Show spinners by incrementing a global counter, hide when count hits zero</li><li><strong>Logging</strong> — Log every request/response for debugging and analytics</li><li><strong>Request modification</strong> — Add timestamps, version headers, request IDs for tracing</li><li><strong>Caching</strong> — Return cached data for GET requests, skip the network entirely</li><li><strong>Retry logic</strong> — Automatically retry failed requests with exponential backoff</li><li><strong>Response transformation</strong> — Unwrap API responses, normalize data shape</li></ul><p>Each of these, without interceptors, would need to be duplicated across 20+ components. With interceptors, it’s centralized, testable, and maintainable.</p><h3>Part 2: The Interceptor Mental Model</h3><p>Here’s how to think about request/response flow:</p><pre>┌─────────────────────────────────────────────────────────────┐<br>│ Your Component: this.http.get(&#39;/api/users&#39;)                 │<br>└──────────────────────────┬──────────────────────────────────┘<br>                           │<br>                           ▼<br>        ┌──────────────────────────────────────┐<br>        │  Request Interceptor #1              │<br>        │  (add auth header, request ID, etc)  │<br>        └──────────────────┬───────────────────┘<br>                           │<br>                           ▼<br>        ┌──────────────────────────────────────┐<br>        │  Request Interceptor #2              │<br>        │  (maybe cache check, logging)        │<br>        └──────────────────┬───────────────────┘<br>                           │<br>                           ▼<br>                  ┌─────────────────┐<br>                  │ Network Request │<br>                  │ (actual HTTP)   │<br>                  └─────────┬───────┘<br>                           │<br>                           ▼<br>        ┌──────────────────────────────────────┐<br>        │  Response Interceptor #2             │<br>        │  (runs in *reverse* order)           │<br>        └──────────────────┬───────────────────┘<br>                           │<br>                           ▼<br>        ┌──────────────────────────────────────┐<br>        │  Response Interceptor #1             │<br>        │  (final processing)                  │<br>        └──────────────────┬───────────────────┘<br>                           │<br>                           ▼<br>┌─────────────────────────────────────────────────────────────┐<br>│ Your Component: .then(data =&gt; console.log(data))            │<br>└─────────────────────────────────────────────────────────────┘</pre><p><strong>Key insight:</strong> Multiple interceptors run in <em>sequence</em> on the request, then in <em>reverse order</em> on the response. This matters when one interceptor depends on another.</p><h3>Part 3: Request Interceptors</h3><p>A request interceptor runs <em>before</em> the HTTP request leaves your app. You can:</p><ul><li>Modify the request (add headers, change the URL, add body data)</li><li>Reject the request entirely (throw an error or return a rejection)</li><li>Skip the network and return cached data</li><li>Track the request (for loading counters, analytics)</li></ul><p><strong>General structure:</strong></p><pre>// Pseudocode — exact syntax varies by framework<br>const requestInterceptor = (config) =&gt; {<br>  // Modify the config object<br>  config.headers.Authorization = `Bearer ${token}`;<br>  config.headers[&#39;X-Request-ID&#39;] = generateRequestId();</pre><pre>  // Return the modified config to let it continue<br>  return config;</pre><pre>  // Or reject it (this stops the request):<br>  // throw new Error(&#39;Request blocked&#39;);<br>};</pre><h3>Common Request Interceptor Patterns</h3><p><strong>Pattern 1: Adding auth headers</strong></p><pre>// Every request gets a JWT token<br>interceptor.request = (config) =&gt; {<br>  const token = localStorage.getItem(&#39;access_token&#39;);<br>  if (token) {<br>    config.headers.Authorization = `Bearer ${token}`;<br>  }<br>  return config;<br>};</pre><p><strong>Pattern 2: Adding metadata</strong></p><pre>// Add a unique request ID and timestamp for tracing<br>interceptor.request = (config) =&gt; {<br>  config.headers[&#39;X-Request-ID&#39;] = `req-${Date.now()}-${Math.random()}`;<br>  config.headers[&#39;X-Timestamp&#39;] = new Date().toISOString();<br>  return config;<br>};</pre><p><strong>Pattern 3: Modifying the URL</strong></p><pre>// Add query params or change the base URL dynamically<br>interceptor.request = (config) =&gt; {<br>  config.url = `${process.env.REACT_APP_API_URL}${config.url}`;<br>  // Also works: config.params = { ...config.params, v: &#39;2&#39; };<br>  return config;<br>};</pre><h3>Part 4: Response Interceptors</h3><p>A response interceptor runs <em>after</em> the HTTP response returns. Here’s what you can do:</p><ul><li>Transform the response (unwrap nested data, normalize shape)</li><li>Check the status code and decide what to do</li><li>Retry the request if it failed</li><li>Refresh auth tokens if they’ve expired</li><li>Log the response</li><li>Throw errors for upstream .catch() handlers</li></ul><p><strong>General structure:</strong></p><pre>const responseInterceptor = {<br>  success: (response) =&gt; {<br>    // Handle 2xx responses<br>    // Maybe unwrap the data<br>    return response.data; // or return response as-is<br>  },</pre><pre>  error: (error) =&gt; {<br>    // Handle 4xx, 5xx responses<br>    // Maybe retry, refresh token, or transform the error<br>    throw error; // or return recovery<br>  }<br>};</pre><h3>Common Response Interceptor Patterns</h3><p><strong>Pattern 1: Unwrapping API responses</strong></p><pre>// Many APIs wrap data like: { status: &#39;ok&#39;, data: [...], errors: null }<br>// Unwrap to just get the data<br>interceptor.response.success = (response) =&gt; {<br>  return response.data.data; // Flatten the response<br>};</pre><p><strong>Pattern 2: Handling specific status codes</strong></p><pre>interceptor.response.error = (error) =&gt; {<br>  if (error.response?.status === 401) {<br>    // Token expired — refresh it<br>    return refreshTokenAndRetry(error.config);<br>  }</pre><pre>  if (error.response?.status === 429) {<br>    // Rate limited — retry after delay<br>    return retryWithBackoff(error.config);<br>  }</pre><pre>  // For other errors, rethrow<br>  throw error;<br>};</pre><p><strong>Pattern 3: Logging</strong></p><pre>interceptor.response.success = (response) =&gt; {<br>  console.log(`✅ ${response.config.method.toUpperCase()} ${response.config.url}`);<br>  return response.data;<br>};</pre><pre>interceptor.response.error = (error) =&gt; {<br>  console.error(<br>    `❌ ${error.config.method.toUpperCase()} ${error.config.url}`,<br>    error.response?.status,<br>    error.message<br>  );<br>  throw error;<br>};</pre><h3>Part 5: Common Interceptor Use Cases</h3><h3>Use Case 1: Global Authentication</h3><pre>// Every request automatically includes the user&#39;s token<br>// No component needs to think about auth</pre><pre>const authInterceptor = (config) =&gt; {<br>  const token = getStoredToken();<br>  if (token) {<br>    config.headers.Authorization = `Bearer ${token}`;<br>  }<br>  return config;<br>};</pre><h3>Use Case 2: Handling 401 (Token Expired)</h3><pre>// If the server says &quot;your token expired,&quot; refresh it and retry<br>const handleUnauthorized = async (error) =&gt; {<br>  if (error.response?.status === 401) {<br>    try {<br>      const newToken = await refreshAccessToken();<br>      storeToken(newToken);</pre><pre>      // Retry the original request with new token<br>      error.config.headers.Authorization = `Bearer ${newToken}`;<br>      return httpClient.request(error.config);<br>    } catch {<br>      // Refresh failed — log the user out<br>      redirectToLogin();<br>      throw error;<br>    }<br>  }<br>  throw error;<br>};</pre><h3>Use Case 3: Loading State Management</h3><pre>let activeRequests = 0;</pre><pre>const loadingInterceptor = {<br>  request: (config) =&gt; {<br>    activeRequests++;<br>    showLoadingSpinner(); // Assume this function exists<br>    return config;<br>  },</pre><pre>  response: {<br>    success: (response) =&gt; {<br>      activeRequests--;<br>      if (activeRequests === 0) hideLoadingSpinner();<br>      return response;<br>    },</pre><pre>    error: (error) =&gt; {<br>      activeRequests--;<br>      if (activeRequests === 0) hideLoadingSpinner();<br>      throw error;<br>    }<br>  }<br>};</pre><h3>Use Case 4: Retry with Exponential Backoff</h3><pre>const retryInterceptor = {<br>  response: {<br>    error: async (error) =&gt; {<br>      // Only retry on specific status codes (5xx, timeout, etc)<br>      const shouldRetry = <br>        error.response?.status &gt;= 500 || <br>        error.code === &#39;ECONNABORTED&#39;;</pre><pre>      if (!shouldRetry || error.config.retryCount &gt;= 3) {<br>        throw error;<br>      }</pre><pre>      error.config.retryCount = (error.config.retryCount || 0) + 1;<br>      const delay = Math.pow(2, error.config.retryCount) * 1000; // 2s, 4s, 8s</pre><pre>      await new Promise(resolve =&gt; setTimeout(resolve, delay));<br>      return httpClient.request(error.config);<br>    }<br>  }<br>};</pre><h3>Use Case 5: Caching GET Requests</h3><pre>const cache = new Map();</pre><pre>const cachingInterceptor = {<br>  request: (config) =&gt; {<br>    // Only cache GET requests<br>    if (config.method === &#39;get&#39; &amp;&amp; cache.has(config.url)) {<br>      // Return cached response — skip the network entirely<br>      const cachedResponse = cache.get(config.url);<br>      return Promise.resolve(cachedResponse);<br>    }<br>    return config;<br>  },</pre><pre>  response: {<br>    success: (response) =&gt; {<br>      if (response.config.method === &#39;get&#39;) {<br>        cache.set(response.config.url, response);<br>      }<br>      return response;<br>    }<br>  }<br>};</pre><h3>Part 6: Interceptor vs Middleware</h3><p><strong>Middleware</strong> (like Express middleware) runs on the <em>server</em>.<br><strong>Interceptors</strong> run on the <em>client</em>, in the browser (or Node.js if you’re using an HTTP client there).</p><p>AspectMiddlewareInterceptor<strong>Where</strong>Server-sideClient-side<strong>Runs on</strong>Every incoming request to the serverEvery outgoing/incoming request from the app<strong>Controls</strong>Request routing, authentication, loggingRequest headers, response transformation, caching<strong>Framework</strong>Express, Koa, Django, etc.Axios, Fetch API, Angular HTTP client<strong>Use for</strong>Rate limiting, parsing body, CORSAuth tokens, error handling, retries</p><p><strong>When you need both:</strong></p><pre>Client App<br>    │<br>    ├─ Interceptor (add auth token)<br>    │<br>    ▼ (Network)<br>Server<br>    ├─ Middleware (verify token, log request)<br>    │<br>    ▼ (Route handler)<br>Database</pre><p>Good architecture uses <em>both</em>: interceptors handle client-side concerns (auth, caching, retries), middleware handles server-side concerns (CORS, body parsing, rate limiting).</p><h3>Part 7: React and HTTP Clients</h3><p>React doesn’t have built-in interceptors like Angular does. Instead, you use HTTP libraries like <strong>Axios</strong> or custom hooks wrapping the <strong>Fetch API</strong>.</p><h3>Why Axios?</h3><p>Axios is popular because:</p><ol><li>Simple interceptor syntax (built-in support)</li><li>Automatic JSON transformation</li><li>Request cancellation (useful for cleanup)</li><li>Timeout support</li></ol><h3>Alternative: Fetch + Custom Hook</h3><p>You <em>can</em> build interceptors with Fetch, but it requires more boilerplate. Here’s the pattern:</p><pre>// Custom HTTP client using Fetch<br>class HttpClient {<br>  constructor() {<br>    this.requestInterceptors = [];<br>    this.responseInterceptors = [];<br>  }</pre><pre>  async request(url, options = {}) {<br>    // Run request interceptors<br>    let config = { url, ...options };<br>    for (const interceptor of this.requestInterceptors) {<br>      config = await interceptor(config);<br>    }</pre><pre>    // Make request<br>    const response = await fetch(config.url, config);</pre><pre>    // Run response interceptors<br>    let result = response;<br>    for (const interceptor of this.responseInterceptors) {<br>      result = await interceptor(result);<br>    }</pre><pre>    return result;<br>  }<br>}</pre><p>For this guide, we’ll focus on <strong>Axios</strong> because it’s simpler and more widely used in React apps. The concepts apply to Fetch or other clients too.</p><h3>Part 8: React + Axios Setup</h3><h3>Step 1: Install Axios</h3><pre>npm install axios</pre><h3>Step 2: Create an Axios Instance</h3><pre>// api/client.js<br>import axios from &#39;axios&#39;;</pre><pre>export const httpClient = axios.create({<br>  baseURL: process.env.REACT_APP_API_URL,<br>  timeout: 10000, // 10 second timeout<br>});</pre><pre>export default httpClient;</pre><p>Why create an instance instead of using axios.default?</p><ul><li>You can have <em>multiple</em> HTTP clients with <em>different</em> interceptors (e.g., one for your API, one for third-party services)</li><li>Easier to test (you can mock the instance)</li><li>Cleaner separation of concerns</li></ul><h3>Step 3: Add Your First Interceptor</h3><pre>// api/client.js<br>import axios from &#39;axios&#39;;</pre><pre>const httpClient = axios.create({<br>  baseURL: process.env.REACT_APP_API_URL,<br>});</pre><pre>// Request interceptor: add auth token<br>httpClient.interceptors.request.use(<br>  (config) =&gt; {<br>    const token = localStorage.getItem(&#39;access_token&#39;);<br>    if (token) {<br>      config.headers.Authorization = `Bearer ${token}`;<br>    }<br>    return config;<br>  },<br>  (error) =&gt; {<br>    // If something fails *before* the request is sent, handle it here<br>    return Promise.reject(error);<br>  }<br>);</pre><pre>// Response interceptor: handle errors<br>httpClient.interceptors.response.use(<br>  (response) =&gt; {<br>    // Any 2xx status code comes here<br>    return response.data; // Unwrap the data<br>  },<br>  (error) =&gt; {<br>    // Any non-2xx status code comes here<br>    console.error(&#39;API Error:&#39;, error.response?.status, error.message);<br>    return Promise.reject(error);<br>  }<br>);</pre><pre>export default httpClient;</pre><h3>Step 4: Use in Components</h3><pre>// components/UserList.jsx<br>import { useEffect, useState } from &#39;react&#39;;<br>import httpClient from &#39;../api/client&#39;;</pre><pre>export default function UserList() {<br>  const [users, setUsers] = useState([]);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(null);</pre><pre>  useEffect(() =&gt; {<br>    const fetchUsers = async () =&gt; {<br>      setLoading(true);<br>      try {<br>        // httpClient automatically applies all interceptors<br>        const data = await httpClient.get(&#39;/users&#39;);<br>        setUsers(data);<br>      } catch (err) {<br>        setError(err.message);<br>      } finally {<br>        setLoading(false);<br>      }<br>    };</pre><pre>    fetchUsers();<br>  }, []);</pre><pre>  if (loading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Error: {error}&lt;/p&gt;;</pre><pre>  return (<br>    &lt;ul&gt;<br>      {users.map(user =&gt; (<br>        &lt;li key={user.id}&gt;{user.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>That’s it. The token is automatically included. Errors are automatically logged. Your component stays simple.</p><h3>Part 9: Axios Request Interceptor Deep Dive</h3><h3>Adding Multiple Headers</h3><pre>httpClient.interceptors.request.use((config) =&gt; {<br>  const token = localStorage.getItem(&#39;access_token&#39;);</pre><pre>  // Add auth<br>  if (token) {<br>    config.headers.Authorization = `Bearer ${token}`;<br>  }</pre><pre>  // Add request ID for tracing (helps with debugging)<br>  config.headers[&#39;X-Request-ID&#39;] = generateUUID();</pre><pre>  // Add API version<br>  config.headers[&#39;X-API-Version&#39;] = &#39;2.0&#39;;</pre><pre>  // Add user language preference<br>  config.headers[&#39;Accept-Language&#39;] = getUserLanguage();</pre><pre>  return config;<br>});</pre><h3>Conditionally Adding Headers</h3><pre>// Only add auth headers for your own API, not for third-party requests<br>httpClient.interceptors.request.use((config) =&gt; {<br>  const isInternalAPI = config.url.startsWith(&#39;/api&#39;);</pre><pre>  if (isInternalAPI) {<br>    const token = localStorage.getItem(&#39;access_token&#39;);<br>    if (token) {<br>      config.headers.Authorization = `Bearer ${token}`;<br>    }<br>  }</pre><pre>  return config;<br>});</pre><h3>Logging Request Details</h3><pre>httpClient.interceptors.request.use((config) =&gt; {<br>  const timestamp = new Date().toISOString();<br>  const method = config.method.toUpperCase();</pre><pre>  console.log(`[${timestamp}] 📤 ${method} ${config.url}`);<br>  console.log(&#39;Headers:&#39;, config.headers);<br>  if (config.data) console.log(&#39;Body:&#39;, config.data);</pre><pre>  return config;<br>});</pre><h3>Handling Request Errors (Rare)</h3><p>Request errors happen when:</p><ul><li>Headers are invalid</li><li>Request can’t be constructed</li><li>Local validation fails</li></ul><pre>httpClient.interceptors.request.use(<br>  (config) =&gt; {<br>    // ✅ Happy path<br>    return config;<br>  },<br>  (error) =&gt; {<br>    // ❌ Error path — this rarely happens, but handle it<br>    console.error(&#39;Request construction failed:&#39;, error);<br>    return Promise.reject(error);<br>  }<br>);</pre><h3>Part 10: Axios Response Interceptor Deep Dive</h3><h3>Unwrapping Nested API Responses</h3><p>Most APIs wrap their responses. Your interceptor can flatten them:</p><pre>// API returns: { success: true, data: [...], errors: null, meta: { page: 1 } }<br>// Your app should just get the array</pre><pre>httpClient.interceptors.response.use(<br>  (response) =&gt; {<br>    // Assume this shape and unwrap it<br>    if (response.data?.data !== undefined) {<br>      return response.data.data;<br>    }<br>    // Fallback to raw response<br>    return response.data;<br>  }<br>);</pre><h3>Logging Responses</h3><pre>httpClient.interceptors.response.use(<br>  (response) =&gt; {<br>    const method = response.config.method.toUpperCase();<br>    const status = response.status;<br>    const url = response.config.url;</pre><pre>    console.log(`✅ ${status} ${method} ${url}`);<br>    return response.data;<br>  },<br>  (error) =&gt; {<br>    const method = error.config?.method?.toUpperCase() || &#39;UNKNOWN&#39;;<br>    const status = error.response?.status || &#39;ERROR&#39;;<br>    const url = error.config?.url || &#39;UNKNOWN&#39;;</pre><pre>    console.error(`❌ ${status} ${method} ${url} - ${error.message}`);<br>    return Promise.reject(error);<br>  }<br>);</pre><h3>Transforming Response Data</h3><pre>// Transform timestamps to Date objects, format names, etc.<br>httpClient.interceptors.response.use((response) =&gt; {<br>  const data = response.data;</pre><pre>  // If it&#39;s an array of users, transform each<br>  if (Array.isArray(data)) {<br>    return data.map(transformUser);<br>  }</pre><pre>  // If it&#39;s a single user<br>  if (data.id &amp;&amp; data.name) {<br>    return transformUser(data);<br>  }</pre><pre>  return data;<br>});</pre><pre>function transformUser(user) {<br>  return {<br>    ...user,<br>    createdAt: new Date(user.created_at), // Parse timestamp<br>    displayName: user.name.toUpperCase(),  // Format name<br>  };<br>}</pre><h3>Part 11: Handling 401 (Unauthorized) in React</h3><p>This is the production scenario everyone hits: your JWT token expires mid-session. The server rejects it with 401. What do you do?</p><p><strong>Option A: Simple approach — just log them out</strong></p><pre>httpClient.interceptors.response.use(<br>  (response) =&gt; response.data,<br>  (error) =&gt; {<br>    if (error.response?.status === 401) {<br>      // Token expired — clear auth and redirect to login<br>      localStorage.removeItem(&#39;access_token&#39;);<br>      window.location.href = &#39;/login&#39;;<br>    }<br>    return Promise.reject(error);<br>  }<br>);</pre><p><strong>Problem:</strong> Jarring user experience. They lose their work.</p><p><strong>Option B: Smart approach — refresh the token and retry</strong></p><pre>let isRefreshing = false;<br>let failedQueue = [];</pre><pre>const processQueue = (error, token = null) =&gt; {<br>  failedQueue.forEach(prom =&gt; {<br>    if (error) {<br>      prom.reject(error);<br>    } else {<br>      prom.resolve(token);<br>    }<br>  });<br>  failedQueue = [];<br>};</pre><pre>httpClient.interceptors.response.use(<br>  (response) =&gt; response.data,<br>  async (error) =&gt; {<br>    const { config } = error;</pre><pre>    // Only handle 401 for specific endpoints<br>    if (error.response?.status === 401 &amp;&amp; config.url !== &#39;/auth/refresh&#39;) {</pre><pre>      if (!isRefreshing) {<br>        isRefreshing = true;</pre><pre>        try {<br>          // Make refresh request<br>          const { data } = await axios.post(<br>            `${process.env.REACT_APP_API_URL}/auth/refresh`,<br>            { refreshToken: localStorage.getItem(&#39;refresh_token&#39;) }<br>          );</pre><pre>          // Store new token<br>          localStorage.setItem(&#39;access_token&#39;, data.accessToken);</pre><pre>          // Update default header<br>          httpClient.defaults.headers.common.Authorization = <br>            `Bearer ${data.accessToken}`;</pre><pre>          // Resolve queued requests with new token<br>          processQueue(null, data.accessToken);</pre><pre>          // Retry original request<br>          config.headers.Authorization = `Bearer ${data.accessToken}`;<br>          return httpClient(config);</pre><pre>        } catch (refreshError) {<br>          // Refresh failed — clear everything and log out<br>          localStorage.removeItem(&#39;access_token&#39;);<br>          localStorage.removeItem(&#39;refresh_token&#39;);<br>          processQueue(refreshError, null);<br>          window.location.href = &#39;/login&#39;;<br>          return Promise.reject(refreshError);<br>        } finally {<br>          isRefreshing = false;<br>        }<br>      }</pre><pre>      // If already refreshing, queue this request until refresh completes<br>      return new Promise((resolve, reject) =&gt; {<br>        failedQueue.push({ resolve, reject });<br>      }).then((token) =&gt; {<br>        config.headers.Authorization = `Bearer ${token}`;<br>        return httpClient(config);<br>      });<br>    }</pre><pre>    return Promise.reject(error);<br>  }<br>);</pre><p>This is more complex, but it’s production-grade. Here’s what happens:</p><ol><li><strong>First 401 arrives</strong> → Start refresh, queue other failed requests</li><li><strong>More 401s arrive</strong> → They get queued, not all sent at once</li><li><strong>Refresh completes</strong> → Process the queue, retry all queued requests</li><li><strong>Refresh fails</strong> → Log out the user</li></ol><h3>Part 12: Token Refresh in React (Complete Example)</h3><p>Here’s a complete, copy-paste-ready setup:</p><pre>// api/client.js<br>import axios from &#39;axios&#39;;</pre><pre>const httpClient = axios.create({<br>  baseURL: process.env.REACT_APP_API_URL,<br>  timeout: 10000,<br>});</pre><pre>// State for token refresh queue<br>let isRefreshing = false;<br>let refreshSubscribers = [];</pre><pre>// Subscribe to token refresh completion<br>const subscribeTokenRefresh = (callback) =&gt; {<br>  refreshSubscribers.push(callback);<br>};</pre><pre>// Notify all subscribers that token was refreshed<br>const onRefreshed = (token) =&gt; {<br>  refreshSubscribers.forEach(callback =&gt; callback(token));<br>  refreshSubscribers = [];<br>};</pre><pre>// Request interceptor: add auth token<br>httpClient.interceptors.request.use((config) =&gt; {<br>  const token = localStorage.getItem(&#39;access_token&#39;);<br>  if (token) {<br>    config.headers.Authorization = `Bearer ${token}`;<br>  }<br>  return config;<br>});</pre><pre>// Response interceptor: handle 401 and refresh<br>httpClient.interceptors.response.use(<br>  (response) =&gt; response.data,</pre><pre>  async (error) =&gt; {<br>    const { config } = error;</pre><pre>    // Not a 401, or it&#39;s the refresh endpoint itself<br>    if (error.response?.status !== 401 || config.url.includes(&#39;/auth/refresh&#39;)) {<br>      return Promise.reject(error);<br>    }</pre><pre>    if (!isRefreshing) {<br>      isRefreshing = true;</pre><pre>      try {<br>        // Make the refresh request (use raw axios to avoid infinite loops)<br>        const { data } = await axios.post(<br>          `${process.env.REACT_APP_API_URL}/auth/refresh`,<br>          { refreshToken: localStorage.getItem(&#39;refresh_token&#39;) },<br>          { timeout: 10000 }<br>        );</pre><pre>        // Store new tokens<br>        localStorage.setItem(&#39;access_token&#39;, data.accessToken);<br>        if (data.refreshToken) {<br>          localStorage.setItem(&#39;refresh_token&#39;, data.refreshToken);<br>        }</pre><pre>        // Update client&#39;s default header for future requests<br>        httpClient.defaults.headers.common.Authorization = <br>          `Bearer ${data.accessToken}`;</pre><pre>        // Notify subscribers and clear the queue<br>        onRefreshed(data.accessToken);</pre><pre>        // Retry the original request<br>        config.headers.Authorization = `Bearer ${data.accessToken}`;<br>        return httpClient(config);</pre><pre>      } catch (refreshError) {<br>        // Refresh failed — clear tokens and redirect<br>        localStorage.removeItem(&#39;access_token&#39;);<br>        localStorage.removeItem(&#39;refresh_token&#39;);</pre><pre>        onRefreshed(null); // Clear subscribers without token</pre><pre>        // Redirect to login<br>        if (typeof window !== &#39;undefined&#39;) {<br>          window.location.href = &#39;/login&#39;;<br>        }</pre><pre>        return Promise.reject(refreshError);</pre><pre>      } finally {<br>        isRefreshing = false;<br>      }<br>    }</pre><pre>    // While refresh is happening, queue this request<br>    return new Promise((resolve) =&gt; {<br>      subscribeTokenRefresh((token) =&gt; {<br>        if (token) {<br>          // Refresh succeeded, retry with new token<br>          config.headers.Authorization = `Bearer ${token}`;<br>          resolve(httpClient(config));<br>        } else {<br>          // Refresh failed, reject<br>          resolve(Promise.reject(error));<br>        }<br>      });<br>    });<br>  }<br>);</pre><pre>export default httpClient;</pre><p><strong>Usage in a component:</strong></p><pre>// components/Dashboard.jsx<br>import { useEffect, useState } from &#39;react&#39;;<br>import httpClient from &#39;../api/client&#39;;</pre><pre>export default function Dashboard() {<br>  const [data, setData] = useState(null);</pre><pre>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      try {<br>        // If token expired, interceptor handles refresh automatically<br>        const result = await httpClient.get(&#39;/api/dashboard&#39;);<br>        setData(result);<br>      } catch (error) {<br>        // If refresh failed, we get an error<br>        console.error(&#39;Failed to fetch dashboard:&#39;, error);<br>      }<br>    };</pre><pre>    fetchData();<br>  }, []);</pre><pre>  return data ? &lt;div&gt;{/* render */}&lt;/div&gt; : &lt;p&gt;Loading...&lt;/p&gt;;<br>}</pre><h3>Part 13: Common React Interceptor Mistakes</h3><h3>Mistake 1: Adding Interceptors in Every Component</h3><p>❌ <strong>Wrong:</strong></p><pre>// components/UserList.jsx<br>useEffect(() =&gt; {<br>  const interceptor = httpClient.interceptors.request.use((config) =&gt; {<br>    config.headers.Authorization = `Bearer ${token}`;<br>    return config;<br>  });</pre><pre>  return () =&gt; {<br>    httpClient.interceptors.response.eject(interceptor);<br>  };<br>}, [token]);</pre><p>This adds a new interceptor every time the component mounts. You’ll have 50 interceptors by the end of the day.</p><p>✅ <strong>Right:</strong></p><pre>// api/client.js (once, at app startup)<br>httpClient.interceptors.request.use((config) =&gt; {<br>  const token = localStorage.getItem(&#39;access_token&#39;);<br>  if (token) {<br>    config.headers.Authorization = `Bearer ${token}`;<br>  }<br>  return config;<br>});</pre><p>Set up interceptors <em>once</em> when the app starts, not in components.</p><h3>Mistake 2: Infinite Refresh Loops</h3><p>❌ <strong>Wrong:</strong></p><pre>httpClient.interceptors.response.use(<br>  (response) =&gt; response.data,<br>  (error) =&gt; {<br>    // Every 401 tries to refresh, even if refresh itself gets 401<br>    if (error.response?.status === 401) {<br>      return refreshToken().then(() =&gt; httpClient(error.config));<br>    }<br>    return Promise.reject(error);<br>  }<br>);</pre><p>If refreshToken() returns 401 (refresh token expired), you loop forever.</p><p>✅ <strong>Right:</strong></p><pre>if (error.response?.status === 401 &amp;&amp; !error.config.url.includes(&#39;/auth/refresh&#39;)) {<br>  // Skip 401 handling if this *is* the refresh request<br>  return refreshToken().then(() =&gt; httpClient(error.config));<br>}</pre><h3>Mistake 3: Not Unwrapping Responses</h3><p>❌ <strong>Wrong:</strong></p><pre>// Your API returns { data: [...], errors: null, success: true }<br>// You map over response.data.data everywhere<br>const users = response.data.data.map(u =&gt; u.name);</pre><p>Repeated everywhere. Inconsistent. Fragile.</p><p>✅ <strong>Right:</strong></p><pre>// In the response interceptor<br>httpClient.interceptors.response.use((response) =&gt; {<br>  return response.data?.data || response.data;<br>});</pre><pre>// Now in components<br>const users = data.map(u =&gt; u.name); // Clean!</pre><h3>Mistake 4: Swallowing Errors</h3><p>❌ <strong>Wrong:</strong></p><pre>httpClient.interceptors.response.use(<br>  (response) =&gt; response.data,<br>  (error) =&gt; response.data // 🚨 returns undefined!<br>);</pre><p>❌ <strong>Also wrong:</strong></p><pre>httpClient.interceptors.response.use(<br>  (response) =&gt; response.data,<br>  (error) =&gt; null // Returns null instead of error<br>);</pre><p>Errors disappear silently. Debugging becomes a nightmare.</p><p>✅ <strong>Right:</strong></p><pre>httpClient.interceptors.response.use(<br>  (response) =&gt; response.data,<br>  (error) =&gt; {<br>    // Log it for debugging<br>    console.error(&#39;API error:&#39;, error);</pre><pre>    // Handle specific cases<br>    if (error.response?.status === 401) {<br>      // Handle auth<br>    }</pre><pre>    // Always reject for upstream handlers<br>    return Promise.reject(error);<br>  }<br>);</pre><h3>Mistake 5: Blocking on Interceptors</h3><p>❌ <strong>Wrong:</strong></p><pre>httpClient.interceptors.request.use(async (config) =&gt; {<br>  // Synchronous code, not async!<br>  const token = await getTokenFromServer(); // ❌ blocks everything<br>  config.headers.Authorization = `Bearer ${token}`;<br>  return config;<br>});</pre><p>Request interceptors should be synchronous (or resolve immediately). Async logic blocks all requests.</p><p>✅ <strong>Right:</strong></p><pre>// Pre-fetch tokens before the request<br>httpClient.interceptors.request.use((config) =&gt; {<br>  const token = localStorage.getItem(&#39;access_token&#39;);<br>  config.headers.Authorization = `Bearer ${token}`;<br>  return config;<br>});</pre><p>Or refresh tokens proactively before they expire, not in the interceptor.</p><h3>Part 14: Angular and HTTP Interceptors</h3><p>Angular has <em>first-class</em> interceptor support baked into its HTTP client. Unlike React (where you add Axios), Angular’s HttpClient is designed around interceptors from the ground up.</p><h3>Angular Interceptor API</h3><pre>// An interceptor implements the HttpInterceptor interface<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Injectable()<br>export class AuthInterceptor implements HttpInterceptor {<br>  intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>    // Modify request<br>    const authReq = req.clone({<br>      setHeaders: {<br>        Authorization: `Bearer ${token}`<br>      }<br>    });</pre><pre>    // Pass to next interceptor, or network if this is the last one<br>    return next.handle(authReq);<br>  }<br>}</pre><p>Key Angular concepts:</p><ul><li><strong>HttpRequest</strong> — immutable request object (you .clone() it to modify)</li><li><strong>HttpHandler</strong> — next step in the chain (could be another interceptor or the network)</li><li><strong>HttpEvent</strong> — response (could be a full response, a progress event, etc.)</li><li><strong>Observable</strong> — RxJS stream (you can pipe, retry, catch, etc.)</li></ul><h3>Registering Interceptors</h3><pre>// app.config.ts (Angular 14+) or app.module.ts</pre><pre>import { HttpInterceptor, provideHttpClient, withInterceptors } from &#39;@angular/common/http&#39;;</pre><pre>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideHttpClient(<br>      withInterceptors([authInterceptor, errorInterceptor, loadingInterceptor])<br>    ),<br>  ],<br>};</pre><p>Or with the old module-based approach:</p><pre>// app.module.ts<br>import { HttpClientModule, HTTP_INTERCEPTORS } from &#39;@angular/common/http&#39;;</pre><pre>@NgModule({<br>  imports: [HttpClientModule],<br>  providers: [<br>    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },<br>    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },<br>  ],<br>})<br>export class AppModule {}</pre><h3>Part 15: Angular Functional Interceptors (Modern Approach)</h3><p>Angular 15+ introduced <strong>functional interceptors</strong>, which are simpler than class-based ones.</p><pre>// interceptors/auth.interceptor.ts<br>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { AuthService } from &#39;../services/auth.service&#39;;</pre><pre>export const authInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const authService = inject(AuthService);<br>  const token = authService.getToken();</pre><pre>  if (token) {<br>    // Clone and add Authorization header<br>    req = req.clone({<br>      setHeaders: {<br>        Authorization: `Bearer ${token}`<br>      }<br>    });<br>  }</pre><pre>  return next(req);<br>};</pre><p>Much simpler! No class boilerplate, no @Injectable(), no interface to implement.</p><p><strong>Registration:</strong></p><pre>// app.config.ts<br>import { provideHttpClient, withInterceptors } from &#39;@angular/common/http&#39;;<br>import { authInterceptor } from &#39;./interceptors/auth.interceptor&#39;;</pre><pre>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideHttpClient(<br>      withInterceptors([authInterceptor]) // Add as many as you want<br>    ),<br>  ],<br>};</pre><h3>Part 16: Modifying Angular Requests</h3><h3>Adding Headers</h3><pre>export const authInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const token = localStorage.getItem(&#39;access_token&#39;);</pre><pre>  // HttpRequest is immutable — you clone it to modify<br>  const authReq = req.clone({<br>    setHeaders: {<br>      Authorization: token ? `Bearer ${token}` : &#39;&#39;,<br>      &#39;X-Request-ID&#39;: generateRequestId(),<br>      &#39;X-API-Version&#39;: &#39;2.0&#39;,<br>    }<br>  });</pre><pre>  return next(authReq);<br>};</pre><h3>Adding Query Parameters</h3><pre>export const versionInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  // Add v=2 to all requests<br>  const versionedReq = req.clone({<br>    setParams: {<br>      v: &#39;2&#39;<br>    }<br>  });</pre><pre>  return next(versionedReq);<br>};</pre><h3>Modifying URL</h3><pre>export const baseUrlInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  // Only for relative URLs<br>  if (!req.url.startsWith(&#39;http&#39;)) {<br>    const apiUrl = &#39;https://api.example.com&#39;;<br>    req = req.clone({<br>      url: `${apiUrl}${req.url}`<br>    });<br>  }</pre><pre>  return next(req);<br>};</pre><h3>Modifying Body</h3><pre>export const bodyInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  if (req.method === &#39;POST&#39; &amp;&amp; req.body) {<br>    // Add timestamp to all POST requests<br>    const modifiedBody = {<br>      ...req.body,<br>      _timestamp: new Date().toISOString(),<br>    };</pre><pre>    req = req.clone({<br>      body: modifiedBody<br>    });<br>  }</pre><pre>  return next(req);<br>};</pre><h3>Part 17: Angular Response Handling</h3><p>Response interceptors in Angular are handled via RxJS operators on the Observable:</p><pre>import { tap, catchError } from &#39;rxjs/operators&#39;;<br>import { throwError } from &#39;rxjs&#39;;</pre><pre>export const loggingInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  console.log(`📤 ${req.method} ${req.url}`);</pre><pre>  return next(req).pipe(<br>    tap((event) =&gt; {<br>      // Runs on successful response<br>      if (event instanceof HttpResponse) {<br>        console.log(`✅ ${event.status} ${event.statusText}`);<br>      }<br>    }),</pre><pre>    catchError((error) =&gt; {<br>      // Runs on error<br>      console.error(`❌ ${error.status} ${error.statusText}`);<br>      return throwError(() =&gt; error);<br>    })<br>  );<br>};</pre><h3>Unwrapping API Responses</h3><pre>import { map } from &#39;rxjs/operators&#39;;</pre><pre>export const unwrapInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  return next(req).pipe(<br>    map((event) =&gt; {<br>      // Only transform the actual response, not upload/download progress events<br>      if (event instanceof HttpResponse) {<br>        // Unwrap from API response structure<br>        return event.clone({<br>          body: event.body?.data || event.body<br>        });<br>      }<br>      return event;<br>    })<br>  );<br>};</pre><h3>Transforming Data</h3><pre>export const transformInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  return next(req).pipe(<br>    map((event) =&gt; {<br>      if (event instanceof HttpResponse &amp;&amp; Array.isArray(event.body)) {<br>        // Transform each item<br>        return event.clone({<br>          body: event.body.map(item =&gt; ({<br>            ...item,<br>            createdAt: new Date(item.created_at),<br>          }))<br>        });<br>      }<br>      return event;<br>    })<br>  );<br>};</pre><h3>Part 18: Multiple Angular Interceptors and Ordering</h3><p><strong>Order matters.</strong> Interceptors run in the order they’re registered:</p><pre>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideHttpClient(<br>      withInterceptors([<br>        // 1. First: add request ID for tracing<br>        requestIdInterceptor,</pre><pre>        // 2. Second: add auth token<br>        authInterceptor,</pre><pre>        // 3. Third: log requests<br>        loggingInterceptor,</pre><pre>        // 4. Network request happens here</pre><pre>        // 5. Fourth (reverse): handle errors globally<br>        errorInterceptor,</pre><pre>        // 6. Fifth (reverse): transform responses<br>        transformInterceptor,<br>      ])<br>    ),<br>  ],<br>};</pre><p><strong>Request flow (↓):</strong></p><pre>Component<br>  ↓<br>requestIdInterceptor (add X-Request-ID)<br>  ↓<br>authInterceptor (add Authorization)<br>  ↓<br>loggingInterceptor (log to console)<br>  ↓<br>Network</pre><p><strong>Response flow (↑):</strong></p><pre>Network Response<br>  ↓<br>transformInterceptor (unwrap/transform data)<br>  ↓<br>errorInterceptor (catch/retry)<br>  ↓<br>loggingInterceptor (log response)<br>  ↓<br>Component</pre><h3>Part 19: Authentication Interceptor (Angular)</h3><pre>// interceptors/auth.interceptor.ts<br>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { AuthService } from &#39;../services/auth.service&#39;;</pre><pre>export const authInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const authService = inject(AuthService);</pre><pre>  // Get token (could be from localStorage, service, etc.)<br>  const token = authService.getAccessToken();</pre><pre>  if (token) {<br>    // Clone and add Authorization header<br>    req = req.clone({<br>      setHeaders: {<br>        Authorization: `Bearer ${token}`<br>      }<br>    });<br>  }</pre><pre>  return next(req);<br>};</pre><p><strong>Service:</strong></p><pre>// services/auth.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class AuthService {<br>  constructor(private http: HttpClient) {}</pre><pre>  getAccessToken(): string | null {<br>    return localStorage.getItem(&#39;access_token&#39;);<br>  }</pre><pre>  refreshToken(): Observable&lt;{ accessToken: string }&gt; {<br>    const refreshToken = localStorage.getItem(&#39;refresh_token&#39;);<br>    return this.http.post&lt;{ accessToken: string }&gt;(&#39;/auth/refresh&#39;, {<br>      refreshToken<br>    });<br>  }<br>}</pre><h3>Part 20: Error Interceptor (Angular)</h3><pre>// interceptors/error.interceptor.ts<br>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { catchError, throwError } from &#39;rxjs&#39;;<br>import { AuthService } from &#39;../services/auth.service&#39;;<br>import { Router } from &#39;@angular/router&#39;;</pre><pre>export const errorInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const authService = inject(AuthService);<br>  const router = inject(Router);</pre><pre>  return next(req).pipe(<br>    catchError((error) =&gt; {<br>      // Handle specific error codes<br>      if (error.status === 401) {<br>        // Token expired<br>        authService.logout();<br>        router.navigate([&#39;/login&#39;]);<br>      } else if (error.status === 403) {<br>        // Forbidden<br>        router.navigate([&#39;/forbidden&#39;]);<br>      } else if (error.status &gt;= 500) {<br>        // Server error<br>        console.error(&#39;Server error:&#39;, error);<br>      }</pre><pre>      return throwError(() =&gt; error);<br>    })<br>  );<br>};</pre><h3>Part 21: Loading Interceptor (Angular)</h3><pre>// interceptors/loading.interceptor.ts<br>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { tap } from &#39;rxjs/operators&#39;;<br>import { LoadingService } from &#39;../services/loading.service&#39;;</pre><pre>export const loadingInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const loadingService = inject(LoadingService);</pre><pre>  // Start loading<br>  loadingService.show();</pre><pre>  return next(req).pipe(<br>    tap(<br>      () =&gt; {<br>        // Response received<br>        loadingService.hide();<br>      },<br>      (error) =&gt; {<br>        // Error<br>        loadingService.hide();<br>      }<br>    )<br>  );<br>};</pre><p><strong>Service:</strong></p><pre>// services/loading.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { BehaviorSubject } from &#39;rxjs&#39;;</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class LoadingService {<br>  private loadingCount = 0;<br>  isLoading$ = new BehaviorSubject(false);</pre><pre>  show(): void {<br>    this.loadingCount++;<br>    this.isLoading$.next(true);<br>  }</pre><pre>  hide(): void {<br>    this.loadingCount = Math.max(0, this.loadingCount - 1);<br>    if (this.loadingCount === 0) {<br>      this.isLoading$.next(false);<br>    }<br>  }<br>}</pre><p><strong>Component:</strong></p><pre>// components/loading-bar.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br>import { LoadingService } from &#39;../services/loading.service&#39;;</pre><pre>@Component({<br>  selector: &#39;app-loading-bar&#39;,<br>  template: `<br>    &lt;div *ngIf=&quot;loadingService.isLoading$ | async&quot; class=&quot;loading-bar&quot;&gt;<br>      Loading...<br>    &lt;/div&gt;<br>  `,<br>})<br>export class LoadingBarComponent {<br>  constructor(public loadingService: LoadingService) {}<br>}</pre><h3>Part 22: Retry Interceptor (Angular)</h3><pre>// interceptors/retry.interceptor.ts<br>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { catchError, retry, delay } from &#39;rxjs/operators&#39;;<br>import { throwError } from &#39;rxjs&#39;;</pre><pre>export const retryInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  // Only retry GET requests on server errors (5xx)<br>  if (req.method === &#39;GET&#39;) {<br>    return next(req).pipe(<br>      retry({<br>        count: 3,<br>        delay: (error) =&gt; {<br>          // Only retry on 5xx, not on client errors<br>          if (error.status &gt;= 500) {<br>            console.log(`Retrying failed request: ${req.url}`);<br>            return timer(1000); // Wait 1 second before retry<br>          }<br>          return throwError(() =&gt; error);<br>        }<br>      })<br>    );<br>  }</pre><pre>  return next(req);<br>};</pre><p>With exponential backoff:</p><pre>import { timer } from &#39;rxjs&#39;;</pre><pre>export const retryInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  if (req.method === &#39;GET&#39;) {<br>    return next(req).pipe(<br>      retry({<br>        count: 3,<br>        delay: (error, retryCount) =&gt; {<br>          if (error.status &gt;= 500) {<br>            const waitTime = Math.pow(2, retryCount) * 1000; // 1s, 2s, 4s<br>            console.log(`Retrying in ${waitTime}ms...`);<br>            return timer(waitTime);<br>          }<br>          return throwError(() =&gt; error);<br>        }<br>      })<br>    );<br>  }</pre><pre>  return next(req);<br>};</pre><h3>Part 23: Request-Specific Interceptor Behavior</h3><p>Sometimes you want an interceptor to behave differently for specific requests. Two approaches:</p><h3>Approach 1: Check URL</h3><pre>export const authInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  // Only add auth for your API, not for third-party services<br>  const isInternalAPI = req.url.includes(&#39;/api/&#39;);</pre><pre>  if (isInternalAPI) {<br>    const token = localStorage.getItem(&#39;access_token&#39;);<br>    if (token) {<br>      req = req.clone({<br>        setHeaders: { Authorization: `Bearer ${token}` }<br>      });<br>    }<br>  }</pre><pre>  return next(req);<br>};</pre><h3>Approach 2: Use Custom Headers as Flags</h3><p>In your component:</p><pre>// component.ts<br>this.http.get(&#39;/api/users&#39;, {<br>  headers: {<br>    &#39;X-Skip-Auth&#39;: &#39;true&#39; // Custom flag<br>  }<br>}).subscribe(...);</pre><p>In the interceptor:</p><pre>export const authInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  if (req.headers.has(&#39;X-Skip-Auth&#39;)) {<br>    // Remove the flag and skip auth<br>    return next(req.clone({ <br>      headers: req.headers.delete(&#39;X-Skip-Auth&#39;) <br>    }));<br>  }</pre><pre>  const token = localStorage.getItem(&#39;access_token&#39;);<br>  if (token) {<br>    req = req.clone({<br>      setHeaders: { Authorization: `Bearer ${token}` }<br>    });<br>  }</pre><pre>  return next(req);<br>};</pre><h3>Part 24: Caching Interceptor (Angular)</h3><pre>// interceptors/cache.interceptor.ts<br>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { of } from &#39;rxjs&#39;;<br>import { tap } from &#39;rxjs/operators&#39;;</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>class CacheService {<br>  private cache = new Map&lt;string, any&gt;();</pre><pre>  get(key: string): any {<br>    return this.cache.get(key);<br>  }</pre><pre>  set(key: string, value: any): void {<br>    this.cache.set(key, value);<br>  }</pre><pre>  has(key: string): boolean {<br>    return this.cache.has(key);<br>  }<br>}</pre><pre>export const cacheInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const cacheService = inject(CacheService);</pre><pre>  // Only cache GET requests<br>  if (req.method !== &#39;GET&#39;) {<br>    return next(req);<br>  }</pre><pre>  // Check cache<br>  if (cacheService.has(req.url)) {<br>    console.log(`Cache hit: ${req.url}`);<br>    return of(cacheService.get(req.url));<br>  }</pre><pre>  // Not in cache — fetch and cache<br>  return next(req).pipe(<br>    tap((event) =&gt; {<br>      if (event instanceof HttpResponse) {<br>        cacheService.set(req.url, event);<br>      }<br>    })<br>  );<br>};</pre><h3>Part 25: Complex Token Refresh (Angular)</h3><pre>// interceptors/token-refresh.interceptor.ts<br>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { BehaviorSubject, filter, take, switchMap, catchError, throwError } from &#39;rxjs&#39;;<br>import { AuthService } from &#39;../services/auth.service&#39;;</pre><pre>// Shared subject for refresh state<br>const isRefreshing$ = new BehaviorSubject(false);</pre><pre>export const tokenRefreshInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const authService = inject(AuthService);</pre><pre>  return next(req).pipe(<br>    catchError((error) =&gt; {<br>      // Only handle 401 and skip if it&#39;s the refresh endpoint itself<br>      if (error.status !== 401 || req.url.includes(&#39;/auth/refresh&#39;)) {<br>        return throwError(() =&gt; error);<br>      }</pre><pre>      if (!isRefreshing$.value) {<br>        isRefreshing$.next(true);</pre><pre>        return authService.refreshToken().pipe(<br>          switchMap((response) =&gt; {<br>            isRefreshing$.next(false);<br>            // Retry the original request with new token<br>            return next(req.clone({<br>              setHeaders: {<br>                Authorization: `Bearer ${response.accessToken}`<br>              }<br>            }));<br>          }),</pre><pre>          catchError((refreshError) =&gt; {<br>            isRefreshing$.next(false);<br>            authService.logout();<br>            return throwError(() =&gt; refreshError);<br>          })<br>        );<br>      }</pre><pre>      // If already refreshing, wait for it to complete<br>      return isRefreshing$.pipe(<br>        filter(value =&gt; !value), // Wait until refresh completes<br>        take(1),<br>        switchMap(() =&gt; {<br>          // Retry with updated token<br>          const newToken = authService.getAccessToken();<br>          return next(req.clone({<br>            setHeaders: {<br>              Authorization: `Bearer ${newToken}`<br>            }<br>          }));<br>        })<br>      );<br>    })<br>  );<br>};</pre><h3>Part 26: Interceptor Limitations</h3><p>Interceptors are powerful, but they have limits.</p><h3>❌ Can’t intercept:</h3><ol><li><strong>Requests from other tabs/windows</strong> — Interceptors are per-instance</li><li><strong>WebSocket connections</strong> — Different protocol, different API</li><li><strong>Worker/Service Worker requests</strong> — Different thread context</li><li><strong>Form submissions</strong> — Use &lt;form&gt; element directly, not XHR</li><li><strong>GraphQL subscriptions</strong> — Real-time, not interceptable like regular HTTP</li><li><strong>CORS pre-flight requests</strong> — OPTIONS requests handled by browser, not your code</li></ol><h3>❌ Limited scope:</h3><ul><li><strong>Large file uploads</strong> — Interceptors see the whole request, can’t stream progress easily</li><li><strong>Streaming responses</strong> — You intercept the whole response, not chunks</li><li><strong>Cancellation</strong> — Some interceptors can’t properly cancel in-flight requests</li></ul><h3>✅ Workarounds:</h3><p>For WebSocket auth:</p><pre>// Add token to WebSocket handshake manually<br>const token = localStorage.getItem(&#39;access_token&#39;);<br>const socket = io(&#39;https://api.example.com&#39;, {<br>  auth: { token }<br>});</pre><p>For file uploads with progress:</p><pre>// Use progress events, not interceptors<br>const formData = new FormData();<br>formData.append(&#39;file&#39;, file);</pre><pre>this.http.post(&#39;/upload&#39;, formData, {<br>  reportProgress: true,<br>  observe: &#39;events&#39;<br>}).subscribe((event) =&gt; {<br>  if (event.type === HttpEventType.UploadProgress) {<br>    const percentDone = (event.loaded / event.total) * 100;<br>    console.log(`Uploaded ${percentDone}%`);<br>  }<br>});</pre><h3>Part 27: Production Architecture</h3><p>Here’s how a production app structures interceptors:</p><pre>src/<br>├── api/<br>│   ├── client.ts                    # Axios instance (React)<br>│   ├── http.service.ts              # HttpClient setup (Angular)<br>│   └── endpoints.ts                 # API endpoint definitions<br>│<br>├── interceptors/<br>│   ├── auth.interceptor.ts          # Add JWT tokens<br>│   ├── error.interceptor.ts         # Global error handling<br>│   ├── loading.interceptor.ts       # Loading state<br>│   ├── retry.interceptor.ts         # Retry failed requests<br>│   ├── transform.interceptor.ts     # Unwrap responses<br>│   ├── logging.interceptor.ts       # Development logging<br>│   └── index.ts                     # Export all<br>│<br>├── services/<br>│   ├── auth.service.ts              # Token management<br>│   ├── loading.service.ts           # Global loading state<br>│   └── error.service.ts             # Error toasts/notifications<br>│<br>└── App.tsx (React) / app.config.ts (Angular)</pre><p><strong>Best practices:</strong></p><ol><li><strong>One interceptor per concern</strong> — Auth, errors, loading, retries, etc. each get their own</li><li><strong>Service-backed</strong> — Interceptors delegate to services for state management</li><li><strong>Minimal logic</strong> — Keep interceptors thin; put business logic in services</li><li><strong>Testable</strong> — Services are easier to test than interceptor chains</li><li><strong>Documented order</strong> — Comments showing interceptor execution sequence</li><li><strong>Error handling</strong> — Every error interceptor must rethrow or handle explicitly</li><li><strong>No side effects</strong> — Avoid async operations in request interceptors if possible</li></ol><p>Example well-structured setup:</p><pre>// app.config.ts (Angular)<br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    // HTTP with interceptors in order<br>    provideHttpClient(<br>      withInterceptors([<br>        // Layer 1: Request preparation<br>        requestIdInterceptor,           // Add tracing ID<br>        authInterceptor,                // Add auth token<br>        contentTypeInterceptor,         // Add content-type</pre><pre>        // Layer 2: Response handling (reverse order on response)<br>        errorInterceptor,               // Catch and handle errors<br>        transformInterceptor,           // Unwrap responses<br>        cacheInterceptor,               // Cache GET responses<br>      ])<br>    ),</pre><pre>    // Services<br>    AuthService,<br>    ErrorService,<br>    LoadingService,<br>    CacheService,<br>  ],<br>};</pre><h3>Part 28: React vs Angular Comparison</h3><p>AspectReact (Axios)Angular (HttpClient)<strong>Setup</strong>Create instance + add interceptorsRegister via provider or module<strong>Syntax</strong>httpClient.interceptors.request.use()Functional export const or class-based<strong>Request flow</strong>Synchronous middleware chainObservable-based with RxJS<strong>Error handling</strong>Promises and .catch()RxJS catchError operator<strong>Typing</strong>Generics on Axios methodsStrong TypeScript support with generics<strong>State sharing</strong>External state management (Zustand, Redux)RxJS Subjects/Services<strong>Learning curve</strong>Easier for Promises-based developersSteeper, requires RxJS knowledge<strong>Built-in features</strong>Fewer, more DIYComplete HTTP toolkit<strong>Testing</strong>Mock axios instanceMock HttpTestingController<strong>Multiple instances</strong>Can have multiple axios clientsOne HttpClient per module/config</p><p><strong>When to use each:</strong></p><ul><li><strong>React + Axios</strong>: You like simplicity, prefer Promises, want full control</li><li><strong>Angular HttpClient</strong>: You’re in Angular, need RxJS, want built-in patterns</li></ul><h3>Part 29: Final Mental Model</h3><p>Think of HTTP interceptors as a <strong>request/response gateway</strong>:</p><pre>┌─────────────────────────────────────────────────────────────┐<br>│                      Your App                               │<br>├─────────────────────────────────────────────────────────────┤<br>│<br>│  Interceptor Chain = Security + Transformation Pipeline<br>│<br>│  Request Path:    Auth → Logging → Error Handling → Network<br>│  Response Path:   Network → Transform → Logging → App<br>│<br>└─────────────────────────────────────────────────────────────┘</pre><p><strong>Key mental models:</strong></p><ol><li><strong>Interceptors run in sequence</strong> — First added, first to run (on requests)</li><li><strong>Responses run in reverse</strong> — Last added, first to run (on responses)</li><li><strong>Each interceptor either passes it along or handles it</strong> — No silent failures</li><li><strong>Immutable requests</strong> — Clone and return, don’t mutate</li><li><strong>Errors can be handled or rethrown</strong> — You’re in control</li></ol><h3>Conclusion</h3><p>HTTP interceptors are one of those architectural patterns that seem simple at first (“just add a header to every request”) but reveal their power once you understand the full flow. With interceptors, you move cross-cutting concerns out of your components and into a centralized, testable layer.</p><p><strong>In React:</strong> Axios interceptors are straightforward Promise-based middleware. Perfect for adding auth tokens, handling 401 refreshes, and global error handling.</p><p><strong>In Angular:</strong> HttpClient interceptors are RxJS-native, giving you the full power of reactive streams. Slightly more complex syntax, but incredibly flexible once you grok Observables.</p><p><strong>The production pattern:</strong> One interceptor per concern (auth, errors, loading, retry, transform). Each interceptor is thin and delegates to a service for state management. This keeps your code testable, maintainable, and sane.</p><p>Start simple — add auth, then unwrap responses, then handle 401s. Each addition teaches you something new about the flow. Before long, you’ll have a rock-solid HTTP layer that makes your entire app more reliable.</p><p>Now go build something great.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d515521e0832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building AI Agents with LangChain: From Runnables to Production-Ready Tools]]></title>
            <link>https://medium.com/@jackpritomsoren/building-ai-agents-with-langchain-from-runnables-to-production-ready-tools-96486ee76d73?source=rss-17ac2beef113------2</link>
            <guid isPermaLink="false">https://medium.com/p/96486ee76d73</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Jack Pritom Soren]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 12:32:39 GMT</pubDate>
            <atom:updated>2026-08-15T12:32:39.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*YpNOwq3v5UjeopupOtdueQ.jpeg" /></figure><h3>The Problem We’re Solving</h3><p>You’ve got a language model that can follow instructions beautifully — it can write code, answer questions, reason through problems. But here’s the wall every developer hits: <strong>an LLM alone can’t actually <em>do</em> anything in the real world.</strong></p><p>Your model can tell you what the weather is, but it can’t call the weather API. It can explain how to write a database query, but it can’t run one against your actual database. It can suggest which tool to use, but it needs <em>you</em> to wire up the logic to actually invoke that tool.</p><p>That gap — between what an LLM can <em>decide</em> to do and what it can actually <em>execute</em> — is exactly what LangChain agents bridge. And they do it with elegance: you describe your tools, the agent figures out when to use them, and the framework handles all the plumbing.</p><p>But “agents” isn’t one thing. It’s a stack. And before you can build a production agent that talks to APIs, handles errors, and loops with human feedback, you need to understand <strong>Runnables</strong> — the fundamental building block that makes everything work.</p><p>This guide walks you through that entire stack. By the end, you’ll understand not just <em>how</em> to build agents, but <em>why</em> each piece exists and how to compose them for production workloads.</p><h3>What We’ll Cover</h3><ol><li><strong>Runnables: The Foundation</strong> — Understanding the interface that powers everything</li><li><strong>Chaining Components</strong> — Building your first multi-step workflow</li><li><strong>Building a Code Generator</strong> — A practical first agent that chains LLM calls</li><li><strong>Tools: Teaching Agents to Act</strong> — How to give your agent superpowers</li><li><strong>Creating Custom Tools</strong> — Wrapping your Python code so agents can use it</li><li><strong>Tool Binding and Calling</strong> — How the model decides <em>which</em> tool to use</li><li><strong>The Agent Loop: Execution and Control</strong> — Manual agent construction for fine-grained control</li><li><strong>Integrating Real APIs</strong> — A complete weather agent example</li><li><strong>Advanced Patterns and create_agent</strong> — Modern LangChain shortcuts and when to use them</li><li><strong>Pitfalls and Production Lessons</strong> — Common failures and how to avoid them</li></ol><h3>1. Runnables: The Foundation</h3><p>Before agents, before tools, before any of the magic — there’s <strong>Runnable</strong>.</p><p>If you’ve used LangChain, you’ve probably seen this pattern:</p><pre>from langchain_openai import ChatOpenAI</pre><pre>model = ChatOpenAI(model=&quot;gpt-4&quot;)<br>result = model.invoke(&quot;What is 2 + 2?&quot;)</pre><p>That invoke() call? That&#39;s a Runnable. The model is a Runnable. And understanding what Runnables <em>are</em> is the key to everything that follows.</p><h3>What is a Runnable?</h3><p>A <strong>Runnable</strong> is LangChain’s abstraction for anything that takes input, processes it, and returns output. It’s a contract that says: “I can be invoked, streamed, batched, or composed with other things.”</p><p>Think of it like this: if you’ve ever used Unix pipes (cat file | grep pattern | wc -l), Runnables work the same way. Each pipe operation is independent, but you can compose them. Each step doesn&#39;t need to know about the others — it just needs to understand input and output.</p><p>Here’s the key insight: <strong>everything in LangChain is a Runnable</strong>. Models, prompt templates, output parsers, tools, chains — they all implement the same interface. That’s what makes composition so powerful.</p><pre>from langchain_openai import ChatOpenAI<br>from langchain.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser</pre><pre># Each of these is a Runnable<br>prompt = ChatPromptTemplate.from_template(&quot;Tell me a joke about {topic}&quot;)<br>model = ChatOpenAI(model=&quot;gpt-4&quot;)<br>parser = StrOutputParser()</pre><pre># Chain them together using the pipe operator |<br># This creates a new Runnable that chains all three<br>joke_chain = prompt | model | parser</pre><pre># Now invoke it with input<br>result = joke_chain.invoke({&quot;topic&quot;: &quot;debugging&quot;})<br>print(result)<br># Output: &quot;Why do programmers prefer dark mode? Because light attracts bugs!&quot;</pre><p>Notice the | operator. That&#39;s the pipe — it chains Runnables together. When you invoke the final chain, LangChain automatically:</p><ol><li>Passes your input to the first Runnable (prompt)</li><li>Takes that output and passes it to the next (model)</li><li>Takes that output and passes it to the next (parser)</li><li>Returns the final result</li></ol><p>This is declarative composition. You describe the flow, LangChain handles the threading.</p><h3>Why This Matters for Agents</h3><p>Agents are just more complex Runnable chains. An agent is:</p><ul><li>A prompt (Runnable)</li><li>A model (Runnable)</li><li>A tool executor (Runnable)</li><li>Looped until the model says “stop”</li></ul><p>Once you get the Runnable pattern, agents become less mysterious. They’re just composition taken a step further.</p><h3>2. Chaining Components</h3><p>Let’s build something slightly more complex — a chain that combines multiple steps.</p><p>Suppose you’re building a product recommendation system. You need to:</p><ol><li>Take a user’s preferences</li><li>Pass them to an LLM to generate a search query</li><li>Use that query to find products</li><li>Pass the results back to the LLM to write recommendations</li></ol><p>Here’s how you’d structure this with Runnables:</p><pre>from langchain_openai import ChatOpenAI<br>from langchain.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser</pre><pre># Step 1: Generate a search query from preferences<br>query_prompt = ChatPromptTemplate.from_template(<br>    &quot;&quot;&quot;Given these user preferences, generate a concise search query.</pre><pre>User preferences: {preferences}</pre><pre>Search query:&quot;&quot;&quot;<br>)</pre><pre>model = ChatOpenAI(model=&quot;gpt-4&quot;)<br>query_parser = StrOutputParser()</pre><pre># This chain transforms preferences → search query<br>search_query_chain = query_prompt | model | query_parser</pre><pre># Step 2: Mock product search (in reality, this calls an API)<br>def search_products(query):<br>    &quot;&quot;&quot;Simulate a product search. In production, this hits your database.&quot;&quot;&quot;<br>    # Pretend we found these products<br>    return f&quot;Found products matching &#39;{query}&#39;: Laptop Pro 15, Gaming Mouse RGB, USB-C Hub&quot;</pre><pre># Step 3: Generate recommendations from search results<br>recommendation_prompt = ChatPromptTemplate.from_template(<br>    &quot;&quot;&quot;You are a product recommendation expert.</pre><pre>User preferences: {preferences}<br>Search results: {search_results}</pre><pre>Write a brief recommendation based on these results.&quot;&quot;&quot;<br>)</pre><pre>recommendation_chain = recommendation_prompt | model | query_parser</pre><pre># Now compose the entire flow<br>from langchain_core.runnables import RunnablePassthrough</pre><pre># RunnablePassthrough keeps the original input flowing through the chain<br>full_chain = (<br>    RunnablePassthrough.assign(search_results=search_query_chain | (lambda q: search_products(q)))<br>    | recommendation_chain<br>)</pre><pre># Execute it<br>result = full_chain.invoke({&quot;preferences&quot;: &quot;I need a laptop for video editing&quot;})<br>print(result)</pre><p>This is still just a chain — deterministic, no looping. But notice the pattern: you describe the structure, compose Runnables, and invoke the whole thing. <strong>Agents will follow this exact pattern, just with the addition of a loop and the ability to dynamically choose which tool to use.</strong></p><h3>3. Building a Code Generator: A Practical First Agent</h3><p>Let’s build something that feels agent-like: a chain that generates Python code for a user request, and optionally improves it.</p><p>This isn’t a full agent yet (no dynamic tool selection), but it demonstrates the chain patterns you’ll see in real agents.</p><pre>from langchain_openai import ChatOpenAI<br>from langchain.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough</pre><pre>model = ChatOpenAI(model=&quot;gpt-4&quot;)</pre><pre># Step 1: Generate initial code<br>code_gen_prompt = ChatPromptTemplate.from_template(<br>    &quot;&quot;&quot;You are an expert Python developer.<br>Generate clean, well-commented Python code for this request.</pre><pre>Request: {request}</pre><pre>Only output the code, no explanations.&quot;&quot;&quot;<br>)</pre><pre># Step 2: Review and improve the code<br>review_prompt = ChatPromptTemplate.from_template(<br>    &quot;&quot;&quot;Review this Python code for:<br>- Efficiency<br>- Readability<br>- Best practices<br>- Potential bugs</pre><pre>Code:<br>{code}</pre><pre>Provide the improved code with inline comments explaining any changes.&quot;&quot;&quot;<br>)</pre><pre># Compose into a pipeline<br>code_gen_chain = code_gen_prompt | model | StrOutputParser()</pre><pre># This is the key: pass the original request through, while also computing the generated code<br>code_review_chain = (<br>    RunnablePassthrough.assign(code=code_gen_chain)<br>    | review_prompt<br>    | model<br>    | StrOutputParser()<br>)</pre><pre># Execute<br>result = code_review_chain.invoke({<br>    &quot;request&quot;: &quot;Write a function that checks if a number is prime&quot;<br>})</pre><pre>print(result)</pre><p>Here’s what’s happening under the hood:</p><ol><li>RunnablePassthrough.assign() keeps the original input and adds a new field (code) computed by running code_gen_chain</li><li>The enriched input flows to review_prompt</li><li>The model reviews the code</li><li>The parser returns clean text</li></ol><p><strong>This pattern is crucial for agents</strong>: at each step, you’re enriching the context with new information, and that context flows to the next step.</p><h3>4. Tools: Teaching Agents to Act</h3><p>Now we get to the real power. A <strong>Tool</strong> is how you tell an agent: “Here’s something you can do in the real world.”</p><p>Before we build custom tools, let’s understand what a Tool is:</p><pre>from langchain_core.tools import tool</pre><pre># Define a tool using the @tool decorator<br>@tool<br>def get_current_time() -&gt; str:<br>    &quot;&quot;&quot;Get the current date and time.</pre><pre>    This tool is useful when the user asks about the current time,<br>    date, or needs to schedule something.&quot;&quot;&quot;<br>    from datetime import datetime<br>    return datetime.now().isoformat()</pre><pre>@tool<br>def calculator(expression: str) -&gt; str:<br>    &quot;&quot;&quot;Evaluate a mathematical expression.</pre><pre>    Args:<br>        expression: A valid Python math expression (e.g., &#39;2 + 2&#39; or &#39;sqrt(16)&#39;)</pre><pre>    This tool is useful for calculations the model should perform precisely.&quot;&quot;&quot;<br>    try:<br>        # Use Python&#39;s eval (never do this in production with untrusted input!)<br>        result = eval(expression)<br>        return f&quot;Result: {result}&quot;<br>    except Exception as e:<br>        return f&quot;Error: {e}&quot;</pre><pre># Tools are now Runnables<br>print(get_current_time.invoke({}))<br>print(calculator.invoke({&quot;expression&quot;: &quot;2 ** 10&quot;}))</pre><p>Notice the docstrings. <strong>The docstring is what the LLM sees.</strong> It’s your API documentation for the model. Good docstrings = good tool usage.</p><p>A Tool is:</p><ol><li>A callable function</li><li>A name (derived from function name)</li><li>A description (the docstring)</li><li>Input schema (the function parameters)</li><li>A Runnable that can be invoked</li></ol><p>The model will never see your code. It only sees the tool name, description, and parameter names. So write docstrings like you’re explaining it to a non-programmer.</p><h3>5. Creating Custom Tools</h3><p>Let’s build tools for a practical scenario: an assistant that helps with data analysis.</p><pre>from langchain_core.tools import tool<br>import json</pre><pre># Tool 1: Parse CSV-like data<br>@tool<br>def parse_csv_data(data_str: str) -&gt; str:<br>    &quot;&quot;&quot;Parse a CSV string into structured data.</pre><pre>    Args:<br>        data_str: CSV data as a string (comma-separated values)</pre><pre>    Returns JSON representation of the data with column headers and rows.</pre><pre>    Example: If given &quot;name,age\nAlice,30\nBob,25&quot;, returns a JSON array.</pre><pre>    Use this when you need to work with CSV data.&quot;&quot;&quot;<br>    try:<br>        lines = data_str.strip().split(&#39;\n&#39;)<br>        headers = lines[0].split(&#39;,&#39;)<br>        rows = []<br>        for line in lines[1:]:<br>            values = line.split(&#39;,&#39;)<br>            row = {headers[i]: values[i] for i in range(len(headers))}<br>            rows.append(row)<br>        return json.dumps(rows, indent=2)<br>    except Exception as e:<br>        return f&quot;Error parsing CSV: {e}&quot;</pre><pre># Tool 2: Calculate statistics<br>@tool<br>def calculate_statistics(numbers_str: str) -&gt; str:<br>    &quot;&quot;&quot;Calculate basic statistics (mean, median, std dev, min, max) from a list of numbers.</pre><pre>    Args:<br>        numbers_str: Space or comma-separated numbers</pre><pre>    Use this when the user asks for statistics or summary data.&quot;&quot;&quot;<br>    import statistics<br>    try:<br>        # Handle both space and comma separation<br>        numbers = [float(x) for x in numbers_str.replace(&#39;,&#39;, &#39; &#39;).split()]</pre><pre>        return json.dumps({<br>            &quot;count&quot;: len(numbers),<br>            &quot;mean&quot;: statistics.mean(numbers),<br>            &quot;median&quot;: statistics.median(numbers),<br>            &quot;stdev&quot;: statistics.stdev(numbers) if len(numbers) &gt; 1 else 0,<br>            &quot;min&quot;: min(numbers),<br>            &quot;max&quot;: max(numbers)<br>        }, indent=2)<br>    except Exception as e:<br>        return f&quot;Error calculating statistics: {e}&quot;</pre><pre># Tool 3: Filter data<br>@tool<br>def filter_data(json_data: str, field: str, value: str) -&gt; str:<br>    &quot;&quot;&quot;Filter a JSON array by matching a field to a value.</pre><pre>    Args:<br>        json_data: JSON array as a string<br>        field: The field name to filter by<br>        value: The value to match</pre><pre>    Returns JSON array containing only matching rows.</pre><pre>    Example: Filter users by age == 30.&quot;&quot;&quot;<br>    try:<br>        data = json.loads(json_data)<br>        filtered = [row for row in data if str(row.get(field)) == value]<br>        return json.dumps(filtered, indent=2)<br>    except Exception as e:<br>        return f&quot;Error filtering data: {e}&quot;</pre><pre># Collect tools for the agent<br>tools = [parse_csv_data, calculate_statistics, filter_data]</pre><p><strong>Key principles for custom tools:</strong></p><ol><li><strong>Docstrings are your API contract</strong> — the model only sees the name and docstring, not the code</li><li><strong>Keep it simple</strong> — tools should do one thing well, not be mini-applications</li><li><strong>Handle errors gracefully</strong> — return meaningful error messages, not stack traces</li><li><strong>Test independently</strong> — before adding a tool to an agent, verify it works standalone</li><li><strong>Type hints matter</strong> — they become part of the tool schema the model sees</li></ol><h3>6. Tool Binding and Calling</h3><p>This is where it gets interesting. How does the model <em>know</em> to call a tool? And how do we actually invoke it?</p><p>LangChain uses the <strong>function calling</strong> capability of modern LLMs. Here’s the flow:</p><ol><li>You give the model a set of tools</li><li>The user asks a question</li><li>The model sees the user’s request and the list of available tools</li><li>The model decides: “I should call tool X with these parameters”</li><li>LangChain intercepts that decision and actually calls the tool</li><li>The result goes back to the model</li><li>The model generates a response based on the tool result</li></ol><p>Let’s see it in action:</p><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.tools import tool<br>from langchain.tools.render import format_tool_to_openai_function_calls</pre><pre>model = ChatOpenAI(model=&quot;gpt-4&quot;)</pre><pre>@tool<br>def multiply(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Multiply two numbers together.&quot;&quot;&quot;<br>    return a * b</pre><pre>@tool<br>def add(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Add two numbers together.&quot;&quot;&quot;<br>    return a + b</pre><pre>tools = [multiply, add]</pre><pre># Bind tools to the model<br># This tells the model: &quot;You have these tools available, and here&#39;s how to request them&quot;<br>model_with_tools = model.bind_tools(tools)</pre><pre># When we invoke it, the model returns a message with a &quot;tool_call&quot; in it<br>response = model_with_tools.invoke(&quot;What is 5 times 3, plus 7?&quot;)</pre><pre>print(&quot;Response:&quot;, response)<br>print(&quot;Tool calls:&quot;, response.tool_calls)</pre><pre># The response includes:<br># - .content: The text response<br># - .tool_calls: A list of tool invocations the model decided to make<br># Example tool_call:<br># {<br>#     &quot;name&quot;: &quot;multiply&quot;,<br>#     &quot;args&quot;: {&quot;a&quot;: 5, &quot;b&quot;: 3},<br>#     &quot;id&quot;: &quot;call_123&quot;<br># }</pre><p>The key moment: <strong>when you call </strong><strong>invoke(), the model returns immediately with its tool decisions. It doesn&#39;t execute the tools.</strong> That&#39;s your job (or the agent loop&#39;s job, which we&#39;ll see next).</p><p>The model is saying: “Here’s what I want to do next.” You (the programmer) decide whether to actually do it, error-check it, or modify it based on human feedback.</p><h3>7. The Agent Loop: Manual Construction</h3><p>An <strong>agent loop</strong> is how you handle the back-and-forth between the model and tools. The model decides to call a tool, you execute it, you feed the result back to the model, and repeat until the model says “done.”</p><p>Here’s a manual agent loop — this is the essence of what higher-level abstractions hide:</p><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.tools import tool<br>from langchain_core.messages import HumanMessage, ToolMessage, AIMessage</pre><pre># Define tools<br>@tool<br>def search_knowledge_base(query: str) -&gt; str:<br>    &quot;&quot;&quot;Search the company knowledge base for information.</pre><pre>    Args:<br>        query: A search query</pre><pre>    Returns relevant documents.&quot;&quot;&quot;<br>    # Mock implementation<br>    if &quot;python&quot; in query.lower():<br>        return &quot;Document 1: Python Best Practices\nDocument 2: Python Performance Tips&quot;<br>    return &quot;No documents found&quot;</pre><pre>@tool<br>def fetch_docs(doc_id: str) -&gt; str:<br>    &quot;&quot;&quot;Fetch the full content of a document by ID.</pre><pre>    Args:<br>        doc_id: The document identifier</pre><pre>    Returns the full document content.&quot;&quot;&quot;<br>    docs = {<br>        &quot;doc1&quot;: &quot;Python is a high-level language...&quot;,<br>        &quot;doc2&quot;: &quot;Use list comprehensions for performance...&quot;,<br>    }<br>    return docs.get(doc_id, &quot;Document not found&quot;)</pre><pre>tools = [search_knowledge_base, fetch_docs]<br>model = ChatOpenAI(model=&quot;gpt-4&quot;)<br>model_with_tools = model.bind_tools(tools)</pre><pre># The agent loop<br>def run_agent_loop(user_input: str, max_iterations: int = 10):<br>    &quot;&quot;&quot;<br>    Run the agent loop until the model stops requesting tools.</pre><pre>    This manually handles:<br>    - Sending user input to the model<br>    - Detecting tool calls in the response<br>    - Executing tools<br>    - Feeding results back to the model<br>    - Looping until the model says &quot;done&quot;<br>    &quot;&quot;&quot;</pre><pre>    # Start with the user&#39;s message<br>    messages = [HumanMessage(content=user_input)]</pre><pre>    for i in range(max_iterations):<br>        # Get the model&#39;s response (might include tool calls)<br>        response = model_with_tools.invoke(messages)</pre><pre>        # If the model didn&#39;t request any tools, it&#39;s done<br>        if not response.tool_calls:<br>            return response.content</pre><pre>        # Add the model&#39;s response to the message history<br>        # This is important: the model needs to see its own reasoning<br>        messages.append(AIMessage(content=response.content, tool_calls=response.tool_calls))</pre><pre>        # Execute each tool call the model requested<br>        for tool_call in response.tool_calls:<br>            tool_name = tool_call[&#39;name&#39;]<br>            tool_args = tool_call[&#39;args&#39;]</pre><pre>            # Find the tool and execute it<br>            tool = next((t for t in tools if t.name == tool_name), None)<br>            if not tool:<br>                result = &quot;Error: Tool not found&quot;<br>            else:<br>                result = tool.invoke(tool_args)</pre><pre>            # Add the tool result to the message history<br>            # The model will see what the tool returned<br>            messages.append(ToolMessage(<br>                content=result,<br>                tool_call_id=tool_call[&#39;id&#39;]<br>            ))</pre><pre>        print(f&quot;[Iteration {i+1}] Agent decided to call tools. Processing...&quot;)</pre><pre>    return &quot;Max iterations reached&quot;</pre><pre># Run it<br>result = run_agent_loop(&quot;I need to learn about Python performance optimization&quot;)<br>print(&quot;Final answer:&quot;, result)</pre><p>Here’s what’s happening:</p><ol><li><strong>Initial input</strong>: User message goes into the message list</li><li><strong>Model invocation</strong>: Call the model with all messages so far</li><li><strong>Tool decision</strong>: Check if the model decided to use any tools</li><li><strong>Tool execution</strong>: Actually run the tools and capture results</li><li><strong>Feedback loop</strong>: Add tool results back to messages so the model sees what happened</li><li><strong>Repeat</strong>: Next iteration, the model has full context including previous tool results</li></ol><p>The message history is the key. Each iteration, you’re building a transcript:</p><pre>Human: [question]<br>AI: I&#39;ll search for information... [tool_call: search]<br>Tool: [search result]<br>AI: Now I&#39;ll fetch the full document... [tool_call: fetch]<br>Tool: [document content]<br>AI: Based on the documents, here&#39;s what I found...</pre><p>This manual loop teaches you what’s happening. In production, you’ll use LangChain’s AgentExecutor or create_agent, which handles this looping for you. But understanding the manual loop is critical — it&#39;s where bugs appear, where you need human-in-the-loop intervention, and where you can add monitoring.</p><h3>8. Integrating Real APIs: A Complete Weather Agent</h3><p>Let’s build something practical: a weather agent that can:</p><ul><li>Check current weather in a city</li><li>Get a forecast</li><li>Suggest activities based on weather</li></ul><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.tools import tool<br>import requests<br>import json</pre><pre># Real API tools using OpenWeatherMap API<br>@tool<br>def get_current_weather(city: str) -&gt; str:<br>    &quot;&quot;&quot;Get the current weather for a city.</pre><pre>    Args:<br>        city: The city name (e.g., &#39;London&#39;, &#39;Tokyo&#39;)</pre><pre>    Returns weather information including temperature, conditions, and humidity.</pre><pre>    Use this when the user asks about current weather.&quot;&quot;&quot;<br>    try:<br>        # In production, use your actual API key<br>        api_key = &quot;YOUR_OPENWEATHER_API_KEY&quot;<br>        url = f&quot;https://api.openweathermap.org/data/2.5/weather?q={city}&amp;appid={api_key}&amp;units=metric&quot;</pre><pre>        response = requests.get(url, timeout=5)<br>        response.raise_for_status()<br>        data = response.json()</pre><pre>        return json.dumps({<br>            &quot;city&quot;: data.get(&#39;name&#39;),<br>            &quot;temp&quot;: data[&#39;main&#39;][&#39;temp&#39;],<br>            &quot;feels_like&quot;: data[&#39;main&#39;][&#39;feels_like&#39;],<br>            &quot;condition&quot;: data[&#39;weather&#39;][0][&#39;main&#39;],<br>            &quot;humidity&quot;: data[&#39;main&#39;][&#39;humidity&#39;],<br>            &quot;wind_speed&quot;: data[&#39;wind&#39;][&#39;speed&#39;]<br>        })<br>    except requests.RequestException as e:<br>        return f&quot;Error fetching weather: {e}&quot;</pre><pre>@tool<br>def get_weather_forecast(city: str, days: int = 3) -&gt; str:<br>    &quot;&quot;&quot;Get weather forecast for a city.</pre><pre>    Args:<br>        city: The city name<br>        days: Number of days to forecast (1-5)</pre><pre>    Returns forecast data.&quot;&quot;&quot;<br>    try:<br>        api_key = &quot;YOUR_OPENWEATHER_API_KEY&quot;<br>        # Using free tier endpoint<br>        url = f&quot;https://api.openweathermap.org/data/2.5/forecast?q={city}&amp;appid={api_key}&amp;units=metric&quot;<br>        response = requests.get(url, timeout=5)<br>        response.raise_for_status()<br>        data = response.json()</pre><pre>        # Parse into forecast summary<br>        forecasts = []<br>        for item in data[&#39;list&#39;][::8]:  # Every 8 entries = ~1 day<br>            forecasts.append({<br>                &quot;time&quot;: item[&#39;dt_txt&#39;],<br>                &quot;temp&quot;: item[&#39;main&#39;][&#39;temp&#39;],<br>                &quot;condition&quot;: item[&#39;weather&#39;][0][&#39;main&#39;]<br>            })</pre><pre>        return json.dumps(forecasts[:days])<br>    except requests.RequestException as e:<br>        return f&quot;Error fetching forecast: {e}&quot;</pre><pre>@tool<br>def suggest_activity(weather_condition: str, temperature: float) -&gt; str:<br>    &quot;&quot;&quot;Suggest activities based on weather conditions.</pre><pre>    Args:<br>        weather_condition: Weather type (e.g., &#39;Sunny&#39;, &#39;Rainy&#39;, &#39;Cloudy&#39;)<br>        temperature: Temperature in Celsius</pre><pre>    Returns activity suggestions appropriate for the weather.&quot;&quot;&quot;<br>    suggestions = {<br>        &quot;Sunny&quot;: {<br>            &quot;hot&quot;: &quot;🏖️ Beach, outdoor sports, cycling&quot;,<br>            &quot;warm&quot;: &quot;⛳ Golf, hiking, picnic&quot;,<br>            &quot;cool&quot;: &quot;🚴 Jogging, sightseeing&quot;<br>        },<br>        &quot;Rainy&quot;: {<br>            &quot;hot&quot;: &quot;🎬 Indoor activities, museum, shopping&quot;,<br>            &quot;warm&quot;: &quot;📚 Reading, indoor sports&quot;,<br>            &quot;cool&quot;: &quot;☕ Cozy cafes, bookstores&quot;<br>        },<br>        &quot;Cloudy&quot;: {<br>            &quot;hot&quot;: &quot;🎮 Outdoor games, park&quot;,<br>            &quot;warm&quot;: &quot;🎨 Photography, exploring&quot;,<br>            &quot;cool&quot;: &quot;🥾 Hiking, nature walks&quot;<br>        }<br>    }</pre><pre>    # Categorize temperature<br>    temp_cat = &quot;hot&quot; if temperature &gt; 25 else (&quot;warm&quot; if temperature &gt; 15 else &quot;cool&quot;)<br>    weather_suggestions = suggestions.get(weather_condition, suggestions[&quot;Cloudy&quot;])</pre><pre>    return weather_suggestions.get(temp_cat, &quot;Indoor activities recommended&quot;)</pre><pre>tools = [get_current_weather, get_weather_forecast, suggest_activity]</pre><p>Now let’s build the agent:</p><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.messages import HumanMessage, ToolMessage, AIMessage</pre><pre>model = ChatOpenAI(model=&quot;gpt-4&quot;)<br>model_with_tools = model.bind_tools(tools)</pre><pre>def run_weather_agent(user_input: str, max_iterations: int = 10):<br>    &quot;&quot;&quot;Run the weather agent loop.&quot;&quot;&quot;<br>    messages = [HumanMessage(content=user_input)]</pre><pre>    for iteration in range(max_iterations):<br>        response = model_with_tools.invoke(messages)</pre><pre>        # If no tool calls, the model is done<br>        if not response.tool_calls:<br>            print(f&quot;\n✅ Agent response:\n{response.content}&quot;)<br>            return response.content</pre><pre>        # Add model&#39;s message with tool calls<br>        messages.append(AIMessage(content=response.content, tool_calls=response.tool_calls))</pre><pre>        # Execute each tool<br>        for tool_call in response.tool_calls:<br>            tool_name = tool_call[&#39;name&#39;]<br>            tool_args = tool_call[&#39;args&#39;]</pre><pre>            tool = next((t for t in tools if t.name == tool_name), None)<br>            if tool:<br>                print(f&quot;\n🔧 Calling {tool_name} with {tool_args}&quot;)<br>                result = tool.invoke(tool_args)<br>                print(f&quot;📊 Result: {result[:100]}...&quot;)  # Truncate for readability<br>            else:<br>                result = &quot;Error: Tool not found&quot;</pre><pre>            messages.append(ToolMessage(<br>                content=result,<br>                tool_call_id=tool_call[&#39;id&#39;]<br>            ))</pre><pre>    return &quot;Max iterations reached&quot;</pre><pre># Use it<br>run_weather_agent(&quot;What&#39;s the weather like in London? And what activities should I do?&quot;)</pre><p>When you run this, here’s what happens:</p><ol><li>User asks about weather in London</li><li>Agent calls get_current_weather(&quot;London&quot;)</li><li>Agent sees the result (sunny, 18°C)</li><li>Agent calls suggest_activity(&quot;Sunny&quot;, 18)</li><li>Agent synthesizes everything into a response</li></ol><p><strong>The magic</strong>: the agent figured out which tools to call <em>and in what order</em> just by understanding the user’s request and the tool descriptions.</p><h3>9. Advanced Patterns: create_agent and Modern LangChain</h3><p>Manually writing the loop works, but LangChain has abstractions to make this easier. The most practical one is create_agent (or AgentExecutor).</p><pre>from langchain_openai import ChatOpenAI<br>from langchain.agents import create_tool_calling_agent, AgentExecutor<br>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br>from langchain_core.tools import tool</pre><pre># Define your tools (same as before)<br>@tool<br>def get_current_weather(city: str) -&gt; str:<br>    &quot;&quot;&quot;Get the current weather for a city.&quot;&quot;&quot;<br>    # Implementation...<br>    pass</pre><pre>tools = [get_current_weather]<br>model = ChatOpenAI(model=&quot;gpt-4&quot;)</pre><pre># Create a system prompt<br>system_prompt = &quot;&quot;&quot;You are a helpful weather assistant. <br>You have access to weather tools that let you look up current conditions,<br>forecasts, and suggest activities.</pre><pre>When a user asks about weather:<br>1. Look up the current weather<br>2. Provide clear, conversational responses<br>3. If relevant, suggest activities</pre><pre>Always be friendly and practical.&quot;&quot;&quot;</pre><pre># Create the prompt template with a placeholder for agent messages<br>prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, system_prompt),<br>    (&quot;user&quot;, &quot;{input}&quot;),<br>    MessagesPlaceholder(variable_name=&quot;agent_scratchpad&quot;),  # Where tool steps go<br>])</pre><pre># Create the agent<br>agent = create_tool_calling_agent(model, tools, prompt)</pre><pre># Create an executor (this handles the loop for you)<br>agent_executor = AgentExecutor(<br>    agent=agent,<br>    tools=tools,<br>    verbose=True,  # Print each step<br>    max_iterations=10,<br>    handle_parsing_errors=True<br>)</pre><pre># Run it<br>result = agent_executor.invoke({<br>    &quot;input&quot;: &quot;What&#39;s the weather in Tokyo and what should I do?&quot;<br>})</pre><pre>print(result[&quot;output&quot;])</pre><p><strong>What changed:</strong></p><ul><li>Instead of manually writing the loop, AgentExecutor does it for you</li><li>You define the tools and a system prompt</li><li>create_tool_calling_agent builds the agent for you</li><li>You invoke the executor once and it handles all the looping</li></ul><p>This is production code. It handles errors, formats outputs, manages context — all the things you’d have to build manually in the loop.</p><p><strong>When to use </strong><strong>create_agent:</strong></p><ul><li>When you want a standard agent that follows tools until it has an answer</li><li>When you want LangChain to manage the message history</li><li>Most of the time in production</li></ul><p><strong>When to use the manual loop:</strong></p><ul><li>When you need custom logic (e.g., human approval after each step)</li><li>When you need fine-grained control over what happens between tool calls</li><li>When debugging why an agent is making bad tool choices</li></ul><h3>10. Pitfalls and Production Lessons</h3><p>You’ve built agents. Now here’s what bites you in production.</p><h3>Pitfall 1: Ambiguous Tool Descriptions</h3><p>❌ <strong>Bad:</strong></p><pre>@tool<br>def process_data(input: str) -&gt; str:<br>    &quot;&quot;&quot;Process the input data.&quot;&quot;&quot;<br>    pass</pre><p>The model has <em>no idea</em> what this does. It will guess wrong.</p><p>✅ <strong>Good:</strong></p><pre>@tool<br>def calculate_monthly_revenue(year: int, month: int) -&gt; str:<br>    &quot;&quot;&quot;Calculate total revenue for a specific month.</pre><pre>    Args:<br>        year: The year (e.g., 2024)<br>        month: The month (1-12)</pre><pre>    Returns the revenue as a formatted string with currency.</pre><pre>    Use this when the user asks about revenue, earnings, or sales for a specific month.&quot;&quot;&quot;<br>    pass</pre><p>Every tool call the model makes comes from the docstring. Spend time there.</p><h3>Pitfall 2: Tools That Fail Silently or Crash</h3><p>❌ <strong>Bad:</strong></p><pre>@tool<br>def fetch_user(user_id: int) -&gt; dict:<br>    &quot;&quot;&quot;Fetch a user by ID.&quot;&quot;&quot;<br>    response = requests.get(f&quot;https://api.example.com/users/{user_id}&quot;)<br>    return response.json()  # What if user_id doesn&#39;t exist? What if network fails?</pre><p>The agent can’t handle errors. The whole chain breaks.</p><p>✅ <strong>Good:</strong></p><pre>@tool<br>def fetch_user(user_id: int) -&gt; str:<br>    &quot;&quot;&quot;Fetch a user by ID.</pre><pre>    Returns a JSON string with user details or an error message.&quot;&quot;&quot;<br>    try:<br>        response = requests.get(<br>            f&quot;https://api.example.com/users/{user_id}&quot;,<br>            timeout=5<br>        )<br>        response.raise_for_status()<br>        return json.dumps(response.json())<br>    except requests.RequestException as e:<br>        return f&quot;Error fetching user {user_id}: {e}&quot;<br>    except Exception as e:<br>        return f&quot;Unexpected error: {e}&quot;</pre><p>Always return a string (not objects). Always catch errors. Give the model something to work with.</p><h3>Pitfall 3: Infinite Loops</h3><p>An agent can loop forever if:</p><ul><li>The model keeps requesting the same tool with the same arguments</li><li>A tool never gives the model enough information to decide “I’m done”</li><li>The model misunderstands what it’s supposed to do</li></ul><p>Protection:</p><pre>agent_executor = AgentExecutor(<br>    agent=agent,<br>    tools=tools,<br>    max_iterations=10,  # Hard cap — without this, you pay forever<br>    early_stopping_method=&quot;force&quot;,  # Stop after max_iterations<br>    handle_parsing_errors=True<br>)</pre><h3>Pitfall 4: Tool Hallucination</h3><p>The model might call a tool that doesn’t exist or with completely wrong parameters if:</p><ul><li>The tool description is vague</li><li>Parameter names don’t match what the model expects</li><li>The model is confused about what tools are available</li></ul><p>Protection:</p><pre># Be explicit in tool descriptions<br>@tool<br>def search_database(<br>    query: str, <br>    table: str,  # Not &quot;table_name&quot; — name your params clearly<br>    limit: int = 10<br>) -&gt; str:<br>    &quot;&quot;&quot;Search the database for records.</pre><pre>    Args:<br>        query: The search term (e.g., &quot;email LIKE &#39;john%&#39;&quot;)<br>        table: The table name (&#39;users&#39;, &#39;products&#39;, &#39;orders&#39;)<br>        limit: Maximum number of results to return (1-100, default 10)</pre><pre>    This tool searches the database directly.&quot;&quot;&quot;</pre><h3>Pitfall 5: Trusting External APIs Without Timeout</h3><pre># ❌ This will hang if the API is slow or dead<br>response = requests.get(url)</pre><pre># ✅ Always timeout<br>response = requests.get(url, timeout=5)</pre><p>When an API hangs, your agent hangs. Your user waits forever.</p><h3>Pitfall 6: Not Testing Tools Independently</h3><p>Before you add a tool to an agent, test it in isolation:</p><pre># Test the tool by itself first<br>result = fetch_user.invoke({&quot;user_id&quot;: 123})<br>print(result)</pre><pre># Verify it handles errors<br>result = fetch_user.invoke({&quot;user_id&quot;: -1})<br>print(result)</pre><p>Agent debugging is hard. Single-tool debugging is easy.</p><h3>Pitfall 7: Token Bloat from Message History</h3><p>As an agent loops, its message history grows:</p><pre>User: [question]<br>AI: [tool call]<br>Tool: [large result]<br>AI: [tool call]<br>Tool: [large result]<br>...</pre><p>After 10 iterations with large API responses, you’re sending kilobytes of context to the model. This is slow and expensive.</p><p>Protection:</p><pre># Summarize or truncate tool results<br>@tool<br>def fetch_large_dataset(...) -&gt; str:<br>    data = get_data()<br>    # Only return the most relevant fields<br>    summary = {k: v for k, v in data.items() if k in [&#39;id&#39;, &#39;name&#39;, &#39;status&#39;]}<br>    return json.dumps(summary)</pre><h3>Pitfall 8: Not Monitoring What Tools Are Actually Called</h3><p>Add logging:</p><pre>def run_agent_with_logging(user_input, tools, model, max_iterations=10):<br>    messages = [HumanMessage(content=user_input)]</pre><pre>    for iteration in range(max_iterations):<br>        response = model_with_tools.invoke(messages)</pre><pre>        if not response.tool_calls:<br>            return response.content</pre><pre>        messages.append(AIMessage(content=response.content, tool_calls=response.tool_calls))</pre><pre>        for tool_call in response.tool_calls:<br>            # Log what the agent decided<br>            print(f&quot;[AGENT LOG] Iteration {iteration+1}: Called {tool_call[&#39;name&#39;]} with {tool_call[&#39;args&#39;]}&quot;)</pre><pre>            # ... execute tool ...</pre><p>In production, send this to an observability platform (Datadog, New Relic, etc.). You need to see what your agent is doing.</p><h3>11. Conclusion</h3><p>You now understand the entire stack:</p><ul><li><strong>Runnables</strong> are the abstraction that lets you compose operations</li><li><strong>Prompts, models, and parsers</strong> chain together via the | operator</li><li><strong>Tools</strong> are how you give agents agency — they describe what the agent can do</li><li><strong>Tool binding</strong> lets the model request tool execution</li><li><strong>Agent loops</strong> (manual or automated) handle the back-and-forth between the model and tools</li><li><strong>AgentExecutor</strong> and create_agent wrap the loop for production use</li></ul><p>The mental model is simple: describe tools, describe what you want, let the LLM decide which tools to use, execute those tools, feed results back, repeat.</p><p>The complexity comes in production:</p><ul><li>Making tool descriptions so clear the model never misunderstands</li><li>Handling errors gracefully so one bad tool call doesn’t break the chain</li><li>Monitoring what the agent actually does</li><li>Managing context so you don’t waste tokens on massive message histories</li></ul><p>Start with a simple agent — weather, calculator, knowledge-base lookup. Test it thoroughly. Only then add the complexity: human-in-the-loop, custom logic between tool calls, streaming responses.</p><p>The agents you build today are just the start. Tomorrow, you’ll add:</p><ul><li>Retrieval-augmented generation (RAG) for smarter context</li><li>Memory systems so agents learn from past conversations</li><li>Multi-agent systems where agents delegate to each other</li><li>Tool-use patterns that don’t exist yet</li></ul><p>But all of that builds on what you’ve learned here. Get Runnables in your bones. Understand the loop. Write clear tool descriptions. Test everything. Then build.</p><p>The rest is details.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96486ee76d73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Workflow Orchestration: How AI Agents Can Work Like Your Engineering Team]]></title>
            <link>https://medium.com/@jackpritomsoren/ai-workflow-orchestration-how-ai-agents-can-work-like-your-engineering-team-26b20281779e?source=rss-17ac2beef113------2</link>
            <guid isPermaLink="false">https://medium.com/p/26b20281779e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jack Pritom Soren]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 05:15:05 GMT</pubDate>
            <atom:updated>2026-08-14T05:15:05.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjmNGoC8NCcmXcuikfsglQ.png" /></figure><p>Imagine you are a beginner developer.</p><p>You have been asked to build a new feature:</p><blockquote><em>“Add authentication to the application.”</em></blockquote><p>You open your AI coding agent, give it the instruction, and a few moments later it changes ten files.</p><p>The code works.</p><p>But then you start asking yourself:</p><ul><li>Why did it change these files?</li><li>Why did it choose this architecture?</li><li>Why is authentication implemented this way?</li><li>What happens if the database fails?</li><li>Is there a security problem?</li><li>Will this work when the application grows?</li></ul><p>This is one of the biggest problems with AI coding tools.</p><p>The AI can generate code very quickly, but <strong>writing code is only one part of software engineering.</strong></p><p>A senior engineer does much more than coding.</p><p>Before implementation, they think about requirements, architecture, failure cases, security, performance, testing, and maintainability.</p><p>So instead of using AI as a simple code generator, we can design a workflow where different AI agents perform different engineering responsibilities.</p><p>This idea is called <strong>AI Workflow Orchestration</strong>.</p><h3>What Is AI Workflow Orchestration?</h3><p>First, we need to understand the difference between an <strong>AI agent</strong> and an <strong>AI workflow</strong>.</p><p>A simple AI coding agent looks like this:</p><pre>User Request<br>     ↓<br>    AI<br>     ↓<br>   Code</pre><p>You give the AI a task, and it writes the implementation.</p><p>But real software engineering looks more like this:</p><pre>Requirement<br>    ↓<br>Architecture<br>    ↓<br>Planning<br>    ↓<br>Implementation<br>    ↓<br>Testing<br>    ↓<br>Security Review<br>    ↓<br>Performance Review<br>    ↓<br>Code Review<br>    ↓<br>Production Review</pre><p>The idea behind orchestration is simple:</p><blockquote><em>Instead of asking one AI to do everything, give different responsibilities to different agents and create a process connecting them.</em></blockquote><p>This is similar to how a real engineering team works.</p><h3>Meet ELOS</h3><p>A useful way to organize this workflow is the <strong>Engineering Learning Operating System</strong>, or <strong>ELOS</strong>.</p><p>The idea is not to replace the developer with AI.</p><p>Instead, AI acts like a virtual engineering team.</p><p>You can think of different agents as different roles:</p><pre>Product Manager<br>Software Architect<br>Tech Lead<br>Backend Engineer<br>Code Reviewer<br>Security Engineer<br>Performance Engineer<br>QA Engineer<br>DevOps Engineer<br>Engineering Mentor</pre><p>In a real company, these responsibilities may belong to different people.</p><p>In an AI workflow, they can be represented by different agents.</p><p>But there is one rule that should never change:</p><blockquote><strong><em>AI can help make engineering decisions, but the developer must understand and approve them.</em></strong></blockquote><p>The goal is not simply to produce code.</p><p>The goal is to help the developer learn how the code and architecture work.</p><h3>1. Start With a Mentor Agent</h3><p>One of the most useful agents for beginners is a <strong>Mentor Agent</strong>.</p><p>Why?</p><p>Because a beginner often thinks:</p><blockquote><em>“What code should I write?”</em></blockquote><p>A senior engineer usually starts with a different question:</p><blockquote><em>“What problem are we actually solving?”</em></blockquote><p>Suppose we are building authentication.</p><p>Instead of immediately creating an auth.middleware.ts file, the mentor should first explain the problem.</p><p>For example:</p><p>A user wants to access:</p><pre>GET /orders</pre><p>The backend needs to determine:</p><blockquote><em>Who is making this request?</em></blockquote><p>That leads us to a possible flow:</p><pre>Client<br>  ↓<br>Authentication Middleware<br>  ↓<br>Controller<br>  ↓<br>Service<br>  ↓<br>Repository<br>  ↓<br>Database</pre><p>The mentor can then explain why authentication belongs in middleware, why business logic belongs in the service layer, and why database operations belong in the repository layer.</p><p>This changes AI from a <strong>coding machine</strong> into a <strong>learning system</strong>.</p><h3>2. Requirements Agent</h3><p>Now imagine someone says:</p><blockquote><em>“Add user authentication.”</em></blockquote><p>That sounds simple, but it is not a complete requirement.</p><p>There are many questions:</p><pre>How will users log in?</pre><pre>JWT or session?</pre><pre>Will there be access tokens?</pre><pre>Will there be refresh tokens?</pre><pre>Where will tokens be stored?</pre><pre>What happens when a token expires?</pre><pre>What happens with an invalid token?</pre><pre>How will logout work?</pre><pre>Will multiple devices be supported?</pre><pre>Do we need authorization?</pre><p>A <strong>Requirements Agent</strong> turns this vague request into something structured.</p><p>For example:</p><pre>Feature:<br>JWT Authentication</pre><pre>Inputs:<br>email<br>password</pre><pre>Outputs:<br>accessToken<br>refreshToken</pre><pre>Failure Cases:<br>invalid credentials<br>expired token<br>malformed token<br>inactive user</pre><pre>Security:<br>password hashing<br>token validation<br>rate limiting</pre><p>Now the architecture agent has a much clearer problem to solve.</p><h3>3. Architect Agent</h3><p>The Architect Agent asks a different question:</p><blockquote><em>“How should this system be designed?”</em></blockquote><p>Instead of immediately writing code, it might propose:</p><pre>Route<br>  ↓<br>Middleware<br>  ↓<br>Controller<br>  ↓<br>Service<br>  ↓<br>Repository<br>  ↓<br>Database</pre><p>Then it should explain the responsibility of each layer.</p><p>It can also compare different approaches.</p><p>For example:</p><h3>Option A</h3><p>Put authentication logic directly inside controllers.</p><h3>Option B</h3><p>Create reusable authentication middleware.</p><p>Then compare them:</p><pre>Controller Approach<br>       ↓<br>Potential duplication<br>       ↓<br>Harder testing<br>       ↓<br>Harder maintenance</pre><p>versus:</p><pre>Middleware<br>    ↓<br>Reusable<br>    ↓<br>Centralized<br>    ↓<br>Easier testing</pre><p>The important lesson is that architecture is not just about choosing a pattern.</p><p>It is about understanding <strong>why one approach is better for a specific problem.</strong></p><h3>4. Architecture Validator</h3><p>Here is an important improvement.</p><p>Even if the Architect Agent proposes a design, we should not automatically assume the design is correct.</p><p>So we introduce an <strong>Architecture Validator</strong>.</p><p>Its job is to challenge the proposed architecture.</p><p>It asks questions such as:</p><pre>What happens with concurrent requests?</pre><pre>What happens if the database fails?</pre><pre>What happens if Redis becomes unavailable?</pre><pre>Can duplicate operations happen?</pre><pre>Is the endpoint idempotent?</pre><pre>Are there authorization gaps?</pre><pre>Will this scale?</pre><pre>Is there unnecessary coupling?</pre><pre>Is there a simpler design?</pre><p>Think of the two agents like this:</p><pre>Architect:<br>“This is my design.”</pre><pre>Validator:<br>“Now let me try to break your design.”</pre><p>That is much closer to a real engineering review process.</p><h3>5. Planner Agent</h3><p>Once the architecture is approved, we need to turn it into implementation steps.</p><p>That is the job of the <strong>Planner Agent</strong>.</p><p>For example:</p><pre>Step 1<br>Create JWT service</pre><pre>Step 2<br>Create authentication middleware</pre><pre>Step 3<br>Protect required routes</pre><pre>Step 4<br>Update user repository</pre><pre>Step 5<br>Add tests</pre><pre>Step 6<br>Run validation</pre><p>But there is one important detail.</p><p>The planner should also explain <strong>why each file needs to change</strong>.</p><p>For example:</p><pre>auth.service.ts<br>→ Business logic</pre><pre>auth.middleware.ts<br>→ Request authentication</pre><pre>jwt.service.ts<br>→ Token operations</pre><pre>user.repository.ts<br>→ Database access</pre><pre>auth.test.ts<br>→ Behavior verification</pre><p>Now the developer can see the implementation map before any code is written.</p><h3>6. Implementation Agent</h3><p>Only now do we start coding.</p><p>The Implementation Agent can handle the actual code changes.</p><p>But we should give it an important rule:</p><blockquote><strong><em>Do not casually change the approved architecture.</em></strong></blockquote><p>Suppose the agent discovers a problem during implementation.</p><p>It should not silently change the design.</p><p>Instead, it can report:</p><pre>BLOCKED</pre><pre>The current architecture does not support X.</pre><pre>Recommended change:<br>...</pre><pre>Reason:<br>...</pre><pre>Impact:<br>...</pre><p>Then the architecture can be reviewed again.</p><p>This prevents a common AI coding problem:</p><blockquote><em>The AI starts with one plan and quietly changes the architecture while implementing.</em></blockquote><h3>7. Failure Agent: Try to Break the Code</h3><p>Now we reach one of the most interesting parts.</p><p>The implementation is finished.</p><p>A normal coding workflow might say:</p><blockquote><em>“Done.”</em></blockquote><p>But production engineering does not stop there.</p><p>We introduce a <strong>Failure Agent</strong>.</p><p>Its job is simple:</p><blockquote><strong><em>Find ways the implementation could fail.</em></strong></blockquote><p>Imagine we are building a payment system.</p><p>The Failure Agent might ask:</p><pre>What if the user clicks Pay twice?</pre><pre>What if the network times out?</pre><pre>What if payment succeeds but the database update fails?</pre><pre>What if a webhook arrives twice?</pre><pre>What if two workers process the same event?</pre><pre>What if Redis goes down?</pre><pre>What if the database transaction fails?</pre><p>For example:</p><pre>Scenario:<br>User clicks Pay twice.</pre><pre>Expected:<br>Only one charge.</pre><pre>Potential Problem:<br>Two payment requests are processed independently.</pre><pre>Possible Solution:<br>Idempotency key.</pre><p>The agent is not just reviewing the code.</p><p>It is trying to <strong>break the system mentally</strong>.</p><h3>8. Parallel Review Agents</h3><p>After implementation, different agents can inspect the same feature from different perspectives.</p><p>For example:</p><pre>Implementation<br>                      │<br>          ┌───────────┼───────────┐<br>          ▼           ▼           ▼<br>      Security    Performance      QA<br>          │           │           │<br>          └───────────┼───────────┘<br>                      ▼<br>                 Code Review</pre><h3>Security Agent</h3><p>Looks for things like:</p><pre>Authentication bugs<br>Authorization bugs<br>Injection<br>Sensitive data exposure<br>Weak validation<br>Secrets<br>Rate limiting problems</pre><h3>Performance Agent</h3><p>Looks for:</p><pre>N+1 queries<br>Missing indexes<br>Unnecessary API calls<br>Large payloads<br>Slow queries<br>Memory issues<br>Unnecessary loops<br>Caching opportunities</pre><h3>QA Agent</h3><p>Thinks about:</p><pre>Happy path<br>Edge cases<br>Invalid input<br>Boundary cases<br>Failure cases<br>Regression<br>Concurrency</pre><h3>Code Review Agent</h3><p>Checks:</p><pre>Readability<br>Maintainability<br>Architecture<br>Duplication<br>Complexity<br>Naming<br>Tradeoffs</pre><p>The benefit is simple:</p><p><strong>One AI agent may miss something that another perspective catches.</strong></p><h3>9. Review Aggregator</h3><p>Now we have another problem.</p><p>We may have four reports:</p><pre>Security Report<br>Performance Report<br>QA Report<br>Code Review</pre><p>Reading everything manually can become annoying.</p><p>So we introduce a <strong>Review Aggregator</strong>.</p><p>It combines all the findings into one prioritized report.</p><p>For example:</p><pre>CRITICAL<br>1. Authorization vulnerability</pre><pre>HIGH<br>2. Missing database index</pre><pre>MEDIUM<br>3. Missing input validation</pre><pre>LOW<br>4. Naming inconsistency</pre><p>It can also remove duplicate findings.</p><p>Now the developer has one clear review to act on.</p><h3>10. Automatic Fix and Re-check</h3><p>Suppose the reviewers identify a missing database index.</p><p>The Fix Agent implements the change.</p><p>But we should not immediately say:</p><blockquote><em>“Everything is fixed.”</em></blockquote><p>Instead:</p><pre>Implementation<br>      ↓<br>Review<br>      ↓<br>Problems Found<br>      ↓<br>Fix<br>      ↓<br>Re-check</pre><p>This creates a feedback loop.</p><p>If more issues remain:</p><pre>Fix<br> ↓<br>Review<br> ↓<br>Fix<br> ↓<br>Review</pre><p>However, we should avoid infinite loops.</p><p>For example:</p><pre>MAX_REVIEW_ITERATIONS = 3</pre><p>After three automated attempts, human approval becomes necessary.</p><p>This gives us an important safety boundary:</p><blockquote><strong><em>Automation can iterate, but humans remain the final gate.</em></strong></blockquote><h3>11. Production Review</h3><p>A feature can pass tests and still fail in production.</p><p>That’s why we need a <strong>Production Review Agent</strong>.</p><p>It looks beyond the local development environment.</p><p>For example:</p><pre>Logging<br>Monitoring<br>Error handling<br>Database migrations<br>Rollback<br>Environment variables<br>Scaling<br>Caching<br>Observability<br>Deployment<br>Failure recovery</pre><p>Imagine your query takes only 5ms locally.</p><p>Everything looks perfect.</p><p>But production has millions of rows.</p><p>Suddenly the same query may behave very differently because production has different:</p><pre>Data size<br>Indexes<br>Concurrency<br>Network latency<br>Query plans<br>CPU<br>Memory</pre><p>So:</p><blockquote><strong><em>“Works on localhost” does not automatically mean “works in production.”</em></strong></blockquote><h3>12. Reflection Agent</h3><p>Now comes the most important part for beginners.</p><p><strong>Reflection.</strong></p><p>The AI should not simply tell you that the feature is complete.</p><p>It should ask you to explain it.</p><p>For example:</p><pre>Why is this logic inside the service?</pre><pre>Why is authentication handled by middleware?</pre><pre>What happens during concurrent requests?</pre><pre>What happens if the database fails?</pre><pre>How would you scale this?</pre><pre>What tradeoff did we make?</pre><pre>What would you change six months from now?</pre><p>This changes the workflow dramatically.</p><p>Because now the goal is not:</p><blockquote><em>“Did AI finish the feature?”</em></blockquote><p>The goal becomes:</p><blockquote><strong><em>“Can I explain the feature without depending on AI?”</em></strong></blockquote><p>If you cannot explain it, the feature is not really complete from a learning perspective.</p><h3>13. Create an Engineering Journal</h3><p>After every feature, the workflow can generate a small engineering journal.</p><p>For example:</p><pre>Feature</pre><pre>Problem Solved</pre><pre>Architecture</pre><pre>Design Decisions</pre><pre>Tradeoffs</pre><pre>Production Risks</pre><pre>Mistakes Avoided</pre><pre>New Concepts</pre><pre>Knowledge Gaps</pre><pre>Next Topics</pre><p>Over time, this becomes your personal engineering knowledge base.</p><p>Instead of forgetting what you learned after finishing a project, you gradually build a record of your decisions and lessons.</p><h3>14. But There Is a Hidden Problem: Token Usage</h3><p>At this point, you might think:</p><blockquote><em>“This sounds great. Let’s create 20 agents!”</em></blockquote><p>But there is a problem.</p><p><strong>Context and token usage.</strong></p><p>Imagine your repository has 500 files.</p><p>If every agent receives the entire repository:</p><pre>Mentor<br>→ 500 files</pre><pre>Architect<br>→ 500 files</pre><pre>Planner<br>→ 500 files</pre><pre>Implementation<br>→ 500 files</pre><pre>Security<br>→ 500 files</pre><pre>Performance<br>→ 500 files</pre><pre>QA<br>→ 500 files</pre><p>We are repeatedly sending information that most agents do not need.</p><p>This is inefficient and can reduce the quality of the model’s attention because relevant information becomes buried inside unnecessary context.</p><p>So orchestration is not only about creating agents.</p><p>It is also about <strong>managing context intelligently</strong>.</p><h3>15. Give Each Agent Only the Context It Needs</h3><p>One of the easiest optimizations is:</p><blockquote><strong><em>Do not give every agent the entire repository.</em></strong></blockquote><p>For authentication, the Mentor might need:</p><pre>README<br>Architecture docs<br>Relevant auth files<br>Database schema<br>API documentation</pre><p>The Security Agent might need:</p><pre>Auth middleware<br>Auth service<br>User model<br>Routes<br>Configuration</pre><p>The Performance Agent might need:</p><pre>Relevant queries<br>Repository<br>Schema<br>Indexes<br>Performance-sensitive services</pre><p>Each agent receives the minimum useful context.</p><p>That makes the workflow both cheaper and cleaner.</p><h3>16. Pass Artifacts, Not Entire Conversations</h3><p>Another common mistake is passing one agent’s entire conversation to the next agent.</p><p>For example:</p><pre>Mentor Conversation<br>       ↓<br>Architect</pre><pre>Architect Conversation<br>       ↓<br>Planner</pre><pre>Planner Conversation<br>       ↓<br>Implementation</pre><p>That can waste a lot of context.</p><p>Instead, create structured artifacts.</p><p>For example:</p><pre>architecture.md</pre><p>Containing:</p><pre>Decision</pre><pre>Components</pre><pre>Data Flow</pre><pre>API Contract</pre><pre>Database Changes</pre><pre>Tradeoffs</pre><pre>Rejected Alternatives</pre><pre>Risks</pre><p>Now the Planner only needs to read the artifact.</p><p>It does not need the entire conversation that created it.</p><h3>17. Compress Context</h3><p>Sometimes a conversation becomes very long.</p><p>Suppose the Mentor and developer discussed a feature for 20 minutes.</p><p>The Planner probably does not need the complete conversation.</p><p>A compact summary may be enough:</p><pre>Feature:<br>JWT authentication</pre><pre>Requirements:<br>...</pre><pre>Architecture:<br>...</pre><pre>Constraints:<br>...</pre><pre>Decisions:<br>...</pre><pre>Open Questions:<br>...</pre><p>This is called <strong>context compression</strong>.</p><p>The goal is simple:</p><blockquote><em>Keep the information that matters and discard unnecessary conversation history.</em></blockquote><h3>18. Use Different Models for Different Tasks</h3><p>Another optimization is <strong>model routing</strong>.</p><p>Not every task needs the strongest reasoning model.</p><p>Conceptually, you could do something like:</p><pre>Simple classification<br>        ↓<br>Small model</pre><pre>Formatting<br>        ↓<br>Small model</pre><pre>Test generation<br>        ↓<br>Medium model</pre><pre>Architecture<br>        ↓<br>Strong reasoning model</pre><pre>Security-critical review<br>        ↓<br>Strong model</pre><p>The important thing is not to blindly choose the cheapest model.</p><p>Critical engineering decisions deserve an appropriately capable model.</p><p>Cost optimization should never destroy engineering quality.</p><h3>19. Reuse Stable Project Knowledge</h3><p>Some project information does not change frequently.</p><p>For example:</p><pre>Coding standards<br>Architecture principles<br>Project conventions<br>Database conventions<br>API conventions</pre><p>Instead of explaining these rules in every conversation, store them as reusable project instructions.</p><p>For example:</p><pre>.opencode/</pre><pre>instructions/<br>    architecture.md<br>    security.md<br>    testing.md<br>    coding-standards.md</pre><p>Then agents can consistently follow the project’s existing rules.</p><h3>20. Add a Context Manager</h3><p>As workflows become larger, one more role becomes useful:</p><p><strong>Context Manager.</strong></p><p>Its job is to decide:</p><pre>What does this agent actually need?</pre><pre>Which files are relevant?</pre><pre>Which previous decisions matter?</pre><pre>What can be summarized?</pre><pre>What can be discarded?</pre><p>Think of it as the workflow’s <strong>context-budget gatekeeper</strong>.</p><p>Instead of blindly giving every agent everything, it decides what information should actually enter the agent’s context.</p><h3>The Complete Workflow</h3><p>Now we can put everything together.</p><pre>USER<br>                           │<br>                           ▼<br>                        MENTOR<br>                           │<br>                           ▼<br>                      REQUIREMENTS<br>                           │<br>                           ▼<br>                       ARCHITECT<br>                           │<br>                           ▼<br>                ARCHITECTURE VALIDATOR<br>                           │<br>                    ┌──────┴──────┐<br>                    │             │<br>                   FAIL          PASS<br>                    │             │<br>                    └─── Revise   │<br>                                  ▼<br>                               PLANNER<br>                                  │<br>                                  ▼<br>                           CONTEXT MANAGER<br>                                  │<br>                                  ▼<br>                           IMPLEMENTATION<br>                                  │<br>                                  ▼<br>                           FAILURE AGENT<br>                                  │<br>                    ┌─────────────┼─────────────┐<br>                    ▼             ▼             ▼<br>                SECURITY     PERFORMANCE        QA<br>                    │             │             │<br>                    └─────────────┼─────────────┘<br>                                  ▼<br>                              CODE REVIEW<br>                                  │<br>                                  ▼<br>                           REVIEW AGGREGATOR<br>                                  │<br>                           ┌──────┴──────┐<br>                           │             │<br>                          FAIL          PASS<br>                           │             │<br>                           ▼             │<br>                    FIX IMPLEMENTATION  │<br>                           │             │<br>                           └──────┐      │<br>                                  ▼      │<br>                               RE-CHECK ◄┘<br>                                  │<br>                                  ▼<br>                          PRODUCTION REVIEW<br>                                  │<br>                                  ▼<br>                           HUMAN REVIEW<br>                                  │<br>                                  ▼<br>                              REFLECTION<br>                                  │<br>                                  ▼<br>                          LEARNING SUMMARY<br>                                  │<br>                                  ▼<br>                       ENGINEERING JOURNAL<br>                                  │<br>                                  ▼<br>                                DONE</pre><p>This is the key idea of ELOS.</p><h3>The Most Important Rule</h3><p>After everything we have discussed, one principle matters more than the number of agents.</p><blockquote><strong><em>AI can propose. AI can implement. AI can review. But the engineer must understand and approve.</em></strong></blockquote><p>AI-generated code can look correct.</p><p>But:</p><pre>Looks correct<br>      ≠<br>Is correct</pre><p>That is why the workflow needs a human quality gate.</p><p>Ask yourself:</p><pre>Can I explain this implementation?</pre><p>If the answer is no:</p><pre>Don&#39;t accept it yet.</pre><p>If the answer is yes:</p><pre>Continue.</pre><h3>What Is the Real Goal?</h3><p>The future of AI-assisted development is not simply:</p><blockquote><em>“AI writes my code.”</em></blockquote><p>A better vision is:</p><blockquote><strong><em>“AI works with me like an engineering team.”</em></strong></blockquote><p>One agent helps understand requirements.</p><p>Another designs architecture.</p><p>Another challenges the design.</p><p>Another implements the feature.</p><p>Another tries to break it.</p><p>Security checks security.</p><p>Performance checks bottlenecks.</p><p>QA checks edge cases.</p><p>Code review checks maintainability.</p><p>Production review checks real-world risks.</p><p>And finally, the AI asks you:</p><blockquote><strong><em>“Do you actually understand what we built?”</em></strong></blockquote><p>That is the difference between <strong>using AI to generate code</strong> and <strong>using AI to become a better engineer</strong>.</p><h3>Final Thought</h3><p>AI should not make you dependent on generated code.</p><p>It should make you better at:</p><p><strong>thinking, designing, reviewing, debugging, and making engineering decisions.</strong></p><p>The ultimate goal is not to build a system where AI can code without you.</p><p>The ultimate goal is to build a system where, over time, <strong>you become capable of making senior-level engineering decisions yourself.</strong></p><p>That is the real purpose of an Engineering Learning Operating System.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26b20281779e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Explained: How to Give Your LLM a Memory It Can Actually Trust]]></title>
            <link>https://medium.com/@jackpritomsoren/rag-explained-how-to-give-your-llm-a-memory-it-can-actually-trust-5b89708c4406?source=rss-17ac2beef113------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b89708c4406</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jack Pritom Soren]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 13:17:41 GMT</pubDate>
            <atom:updated>2026-07-25T13:17:42.524Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2c_qeMc1DsQEMFr6JY6dw.jpeg" /></figure><p>You’re building a chatbot for a company’s internal documentation — hundreds of pages of engineering specs, HR policies, product guides. You plug in ChatGPT, write a clean system prompt,launch a demo. Someone asks “What’s the reimbursement limit for travel expenses?” and the model confidently answers with a number. The number is wrong. It’s not from your docs — it’s from the model’s general training data, some pattern absorbed from the internet years ago that roughly sounds like a reasonable reimbursement policy.</p><p>This is the fundamental problem with raw LLMs in production: <strong>they don’t know your data.</strong> They know what was in their training set — a snapshot of text from months or years ago, with no awareness of your internal docs, your product specs, your latest pricing, your customer records, or anything else that lives inside your organization. And when they don’t know something, they don’t say “I don’t know” — they say something plausible-sounding that might be completely fabricated.</p><p>The fix has a name: <strong>Retrieval-Augmented Generation</strong>, almost universally abbreviated as <strong>RAG</strong>. The idea is elegant: before asking the model to answer a question, <em>find</em> the relevant pieces of your actual data and hand them to the model as context. Now, instead of guessing, the model is summarizing and reasoning over the real information you provided.</p><p>The gap between “RAG sounds simple” and “RAG actually works reliably in production” is where most teams spend weeks of engineering time. Understanding the full pipeline — every<br>stage, every design decision, every place it quietly breaks — is what this article is about.</p><h3>What We’ll Cover</h3><ol><li>The RAG Mental Model — Why It Works at All</li><li>The Full RAG Development Pipeline (Both Phases)</li><li>Document Loaders — Getting Your Data In</li><li>Text Splitting and Chunking — The Stage Everyone Underestimates</li><li>Embeddings and Vector Stores — Where Your Data Lives at Query Time</li><li>Retrievers — Finding the Right Chunks When It Matters</li><li>Putting It All Together — A Working RAG Chain</li><li>Where RAG Breaks and How to Diagnose It</li></ol><h3>Chapter 1: The RAG Mental Model — Why It Works at All</h3><p>Before code, you need the right mental model, because RAG is counterintuitive until it clicks.</p><p>Think about how <em>you</em> answer questions as a consultant. If someone asks you a question about a client’s contract terms, you don’t try to recall everything from memory — you pull up the contract, skim for the relevant section and answer based on what’s in front of you. You’re not generating from memory; you’re reading and summarizing from a source.</p><p>RAG turns an LLM into that consultant. You build a system that:</p><ol><li><strong>Ingests</strong> your documents (PDFs, web pages, databases, whatever) and stores them in a searchable format.</li><li>When a user asks a question, <strong>retrieves</strong> the most relevant pieces of those documents.</li><li><strong>Augments</strong> the model’s prompt with those retrieved pieces.</li><li>Lets the model <strong>generate</strong> an answer based on the context you just handed it. The LLM’s role shifts from “know everything” to “read what I gave you and reason over it.” That’s a job LLMs are genuinely very good at.</li></ol><pre>Without RAG:<br>User question  →  LLM (guesses from training data)  →  Response (possibly hallucinated)</pre><pre>With RAG:<br>User question  →  Retrieve relevant docs  →  LLM (reads your actual docs)  →  Grounded response</pre><p>This is why RAG is the dominant pattern for enterprise AI applications. It doesn’t eliminate the LLM’s tendency to hallucinate — but it gives the model true ground to stand on,and makes it much easier to audit: if the answer is wrong, you can trace it back to exactly which chunk was retrieved and why.</p><p>The full pipeline has two distinct phases that most beginners conflate into one. Let’s separate them.</p><h3>Chapter 2: The Full RAG Development Pipeline — Two Phases</h3><p>Almost every RAG confusion I’ve seen in teams comes from mixing up what happens <em>before</em> a user ever sends a message versus what happens <em>when</em> they do. These are two fundamentally different processes with different triggers, different costs, and different failure modes.</p><h3>Phase 1 — Indexing (Offline, Runs Once)</h3><p>This is the preparation phase. You run it ahead of time — sometimes once, sometimes on a schedule, sometimes triggered by new document uploads. It does not happen in response to user queries.</p><pre>[ Your Raw Documents ]<br>        │<br>        ▼<br>[ Document Loader ]      ← Pull documents in from wherever they live<br>        │<br>        ▼<br>[ Text Splitter ]        ← Break documents into manageable chunks<br>        │<br>        ▼<br>[ Embedding Model ]      ← Convert each chunk into a numeric vector<br>        │<br>        ▼<br>[ Vector Store ]         ← Store vectors + original text in a searchable database</pre><p>The result: a vector store that contains your entire knowledge base in a format where “find me content similar to this question” is a fast, cheap operation.</p><h3>Phase 2 — Retrieval + Generation (Online, Runs Per Query)</h3><p>This is the live path. It runs every time a user sends a message.</p><pre>[ User Question ]<br>        │<br>        ▼<br>[ Embedding Model ]      ← Convert the question into a vector<br>        │<br>        ▼<br>[ Vector Store Retriever ]  ← Find the chunks most similar to the question<br>        │<br>        ▼<br>[ Prompt Template ]      ← Inject retrieved chunks + question into a prompt<br>        │<br>        ▼<br>[ LLM ]                  ← Generates answer grounded in the retrieved context<br>        │<br>        ▼<br>[ Response to User ]</pre><p>These two phases have completely different performance characteristics. Indexing is slow and expensive per document but runs offline. Retrieval + generation must be fast — it’s the live user experience. Every design decision in RAG falls into one of these two phases. Keep this separation in mind as we go through each component.</p><h3>Chapter 3: Document Loaders — Getting Your Data In</h3><p>The first problem in any real RAG system is always the same: <strong>your data doesn’t live in a clean text file.</strong> It lives in PDFs, Word documents, Notion pages, Confluence wikis,Google Drive folders, databases, Slack threads, web pages, and half a dozen other formats<br> — each requiring different handling to extract usable text.</p><p><strong>Document loaders</strong> in LangChain are the abstraction that handles this — they give you a consistent load() interface regardless of the source, returning a list of Document objects (each containing a page_content string and a metadata dict).</p><pre>from langchain_community.document_loaders import (<br>    PyPDFLoader,         # PDFs — extracts text page by page<br>    WebBaseLoader,       # Web pages — fetches and strips HTML<br>    TextLoader,          # Plain .txt files<br>    CSVLoader,           # Spreadsheets — each row becomes a Document<br>    UnstructuredWordDocumentLoader,  # .docx files<br>    NotionDirectoryLoader,           # Exported Notion workspace<br>)</pre><pre># Every loader shares the same interface — .load() returns List[Document]</pre><pre># Load a PDF — returns one Document per page, with page number in metadata<br>pdf_loader = PyPDFLoader(&quot;engineering_spec.pdf&quot;)<br>pdf_docs = pdf_loader.load()<br># pdf_docs[0].page_content → &quot;Chapter 1: System Architecture...&quot;<br># pdf_docs[0].metadata     → {&quot;source&quot;: &quot;engineering_spec.pdf&quot;, &quot;page&quot;: 0}</pre><pre># Load a web page — strips HTML, extracts main text content<br>web_loader = WebBaseLoader(&quot;https://docs.mycompany.com/api-reference&quot;)<br>web_docs = web_loader.load()</pre><pre># Load a CSV — useful for structured data like FAQs or product catalogs<br>csv_loader = CSVLoader(&quot;product_faq.csv&quot;, source_column=&quot;url&quot;)<br>csv_docs = csv_loader.load()</pre><p>The metadata dict is not an afterthought — it&#39;s critical for production systems. Every document you ingest should carry metadata: its source URL, file name, creation date, author, document type, whatever is relevant. You&#39;ll use this metadata later for filtering (&quot;only retrieve from documents tagged HR policy&quot;) and for citations in your responses (&quot;according to engineering_spec.pdf, page 12&quot;).</p><pre># Always inspect what your loader actually produced before moving on.<br># Loaders fail silently in surprising ways — PDFs with scanned images return empty<br># page_content strings; HTML with JavaScript-rendered content may come back blank.<br>for doc in pdf_docs[:3]:<br>    print(f&quot;Content length: {len(doc.page_content)} chars&quot;)<br>    print(f&quot;Metadata: {doc.metadata}&quot;)<br>    print(f&quot;Preview: {doc.page_content[:200]}&quot;)<br>    print(&quot;---&quot;)</pre><blockquote><em>⚠️ </em><strong><em>Heads up:</em></strong><em> PDFs are the most common source and the most problematic. Scanned PDFs<br>(images of text rather than actual text) will return empty strings with most loaders — <br>you’ll need OCR processing before the text is even extractable. Always validate that<br>your loader is actually getting text, not silence.</em></blockquote><h3>Chapter 4: Text Splitting and Chunking — The Stage Everyone Underestimates</h3><p>Here’s where most RAG beginners make their biggest architectural mistake, because this stage looks trivial and isn’t.</p><p>You have your documents loaded. They might be entire 80-page PDFs or multi-thousand-word web pages. You can’t stuff all of that into a prompt — LLMs have context limits, and even if you could, you <em>don’t want to</em>. You want to retrieve the <em>specific</em> relevant section, not an entire document.</p><p>So you split documents into <strong>chunks</strong> — smaller pieces of text that can be independently retrieved and included in a prompt. The decisions you make here — how big each chunk is, how they overlap, how they respect the document’s natural structure — have a bigger impact on RAG quality than almost any other single variable.</p><h3>Chunk Size: The Core Trade-off</h3><p>This is a genuine tension with no universal right answer:</p><ul><li><strong>Too small</strong> (e.g., 100 tokens): Each chunk has very little context. You might retrieve a sentence that perfectly matches the query but doesn’t contain enough surrounding information to answer it meaningfully. The model gets fragments.</li><li><strong>Too large</strong> (e.g., 2000 tokens): Each chunk contains more context, but semantic similarity search becomes less precise — a chunk about three different topics might score as a moderate match for many queries rather than a strong match for any. You also use more of your LLM’s context window per retrieved chunk.</li><li><strong>Sweet spot in practice:</strong> 200–500 tokens per chunk for most knowledge-base use cases, with experimentation required for your specific content type and query patterns.</li></ul><h3>Chunk Overlap: Handling Boundary Problems</h3><p>When you split at token/character boundaries, you’ll slice through sentences, sometimes mid-thought. The sentence that contains the key information might end up half in chunk 12 and half in chunk 13, and neither chunk retrieves well. <strong>Overlap</strong> addresses this by<br>repeating the last N tokens of each chunk at the start of the next.</p><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter</pre><pre># The workhorse of LangChain splitting — tries to split on natural boundaries<br># first (paragraphs → sentences → words) before falling back to raw characters.<br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=500,      # Target max characters per chunk<br>    chunk_overlap=50,    # Last 50 chars of chunk N repeated at start of chunk N+1<br>    separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot;. &quot;, &quot; &quot;, &quot;&quot;]  # Try these in order<br>)</pre><pre>chunks = splitter.split_documents(pdf_docs)</pre><pre>print(f&quot;Original: {len(pdf_docs)} pages&quot;)<br>print(f&quot;After splitting: {len(chunks)} chunks&quot;)</pre><pre># Good habit: sanity-check your chunks before continuing<br>for i, chunk in enumerate(chunks[:3]):<br>    print(f&quot;\n--- Chunk {i} ({len(chunk.page_content)} chars) ---&quot;)<br>    print(chunk.page_content)</pre><h3>Splitting Strategies: Not All Text Is Flat Prose</h3><p>RecursiveCharacterTextSplitter is the general-purpose default, but different content<br>types benefit from different strategies:</p><pre>from langchain.text_splitter import (<br>    RecursiveCharacterTextSplitter,   # General prose — paragraphs, articles, docs<br>    MarkdownHeaderTextSplitter,       # Markdown — splits on headings, preserves structure<br>    Language,                         # Code — splits on functions/classes, not mid-line<br>)</pre><pre># For technical documentation in Markdown — splits on headers rather than character count<br>md_splitter = MarkdownHeaderTextSplitter(<br>    headers_to_split_on=[<br>        (&quot;#&quot;, &quot;h1&quot;),<br>        (&quot;##&quot;, &quot;h2&quot;),<br>        (&quot;###&quot;, &quot;h3&quot;),<br>    ]<br>)<br># Each resulting chunk carries header metadata — great for citations later</pre><pre># For code repositories — respects function/class boundaries<br>code_splitter = RecursiveCharacterTextSplitter.from_language(<br>    language=Language.PYTHON,<br>    chunk_size=1000,<br>    chunk_overlap=100,<br>)</pre><blockquote><em>💡 </em><strong><em>Pro tip:</em></strong><em> Add the source metadata to every chunk explicitly — once you’ve split<br>200 documents into 5,000 chunks, you need to know which chunk came from where.<br>LangChain’s splitters preserve metadata from the parent </em><em>Document, but always verify.</em></blockquote><h3>Chapter 5: Embeddings and Vector Stores — Where Your Data Lives</h3><p>You now have thousands of text chunks. The next problem: how do you find the chunks <em>relevant</em> to a specific user question, fast, at query time?</p><p>The answer is <strong>semantic search</strong>, and it works through <strong>embeddings</strong>.</p><h3>What Embeddings Actually Are</h3><p>Remember from the first article: each chunk of text can be converted into a vector — a list of hundreds or thousands of numbers — that represents its <em>meaning</em> in mathematical space. This conversion is done by an embedding model (a different, smaller model than your LLM — its only job is text → vector).</p><p>The key property: <strong>semantically similar text produces mathematically similar vectors.</strong> “How do I reset my password?” and “Steps to change my account credentials” are worded completely differently but mean similar things — their embedding vectors will be close together in vector space, close enough to find each other via similarity search.</p><p>This is why RAG can retrieve relevant content even when the user’s question uses completely different words from your documentation. You’re not searching for matching keywords; you’re searching for matching <em>meaning</em>.</p><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.embeddings import HuggingFaceEmbeddings</pre><pre># OpenAI&#39;s embedding model — cloud API, very good quality<br>openai_embeddings = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)</pre><pre># Or a local HuggingFace model — free, runs on your hardware, great for cost-sensitive<br># or privacy-sensitive use cases (your documents never leave your infrastructure) local_embeddings = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)</pre><pre># What actually happens under the hood (you usually don&#39;t call this directly):<br>vector = openai_embeddings.embed_query(&quot;How do I reset my password?&quot;)<br># vector is a list of ~1500 floats — the &quot;meaning fingerprint&quot; of that sentence print(f&quot;Vector dimensions: {len(vector)}&quot;)  # e.g., 1536 for text-embedding-3-small</pre><h3>Vector Stores</h3><p>Embeddings are only useful if you can search through them efficiently. A <strong>vector store</strong> is a database built for this — you insert vectors + their associated text, and at query time you give it a query vector and it returns the N most similar stored vectors.</p><pre>from langchain_community.vectorstores import (<br>    FAISS,       # Facebook AI Similarity Search — in-memory, great for dev/small scale<br>    Chroma,      # Lightweight persistent vector store — good for local development<br>    Pinecone,    # Managed cloud vector database — production scale<br>    Weaviate,    # Open-source cloud/self-hosted — good for complex filtering<br>    pgvector,    # Postgres extension — great if you&#39;re already on Postgres<br>)</pre><pre># Building a FAISS vector store from chunks — this runs your embedding model<br># on every chunk and stores the result. This is the slow, expensive indexing step. <br>from langchain_community.vectorstores import FAISS<br>from langchain_openai import OpenAIEmbeddings</pre><pre>embeddings = OpenAIEmbeddings()</pre><pre># This call: embeds every chunk + builds the search index<br>vectorstore = FAISS.from_documents(<br>    documents=chunks,      # Your split documents from Chapter 4<br>    embedding=embeddings   # The model that converts text → vector<br>)</pre><pre># Persist to disk so you don&#39;t re-embed every time your app restarts<br>vectorstore.save_local(&quot;my_knowledge_base&quot;)</pre><pre># Load it back later — no re-embedding needed<br>vectorstore = FAISS.load_local(&quot;my_knowledge_base&quot;, embeddings,<br>                                allow_dangerous_deserialization=True)</pre><blockquote><em>⚠️ </em><strong><em>Heads up:</em></strong><em> Embedding your entire document set costs money and takes time — <br>OpenAI’s embedding API charges per token, and embedding 10,000 chunks can take minutes.<br>Always persist your vector store to disk (or use a managed service) so the indexing<br>phase runs once, not on every app restart.</em></blockquote><h3>Chapter 6: Retrievers — Finding the Right Chunks When It Matters</h3><p>A <strong>retriever</strong> is the interface that sits in front of your vector store and answers one question: given this query, what chunks should I surface? It’s what Phase 2 of the pipeline calls when a user sends a message.</p><p>The simplest retriever is just a vector store wrapper:</p><pre># The most basic retriever — pure semantic similarity search<br>retriever = vectorstore.as_retriever(<br>    search_type=&quot;similarity&quot;,   # Find the N most semantically similar chunks<br>    search_kwargs={&quot;k&quot;: 4}      # Return the top 4 chunks<br>)</pre><pre># Test it — this is what runs at query time:<br>relevant_chunks = retriever.invoke(&quot;What is the reimbursement limit for travel?&quot;)<br>for chunk in relevant_chunks:<br>    print(chunk.page_content[:300])<br>    print(f&quot;Source: {chunk.metadata.get(&#39;source&#39;, &#39;unknown&#39;)}&quot;)<br>    print(&quot;---&quot;)</pre><p>But “top 4 by similarity” is actually a pretty naive strategy, and there are several retrieval approaches that meaningfully improve quality in practice.</p><h3>MMR — Maximum Marginal Relevance</h3><p>Pure similarity search has a hidden flaw: if your knowledge base has five paragraphs that all say the same thing slightly differently, you’ll retrieve all five of them instead of<br>getting diverse, complementary information. <strong>MMR</strong> trades off between relevance (is this chunk similar to the query?) and diversity (is this chunk different from what I’ve already retrieved?).</p><pre>retriever = vectorstore.as_retriever(<br>    search_type=&quot;mmr&quot;,          # Maximum Marginal Relevance<br>    search_kwargs={<br>        &quot;k&quot;: 4,                  # Return 4 chunks<br>        &quot;fetch_k&quot;: 20,           # Consider top 20 by similarity first<br>        &quot;lambda_mult&quot;: 0.7       # 0 = pure diversity, 1 = pure similarity<br>    }<br>)</pre><h3>Similarity Score Threshold</h3><p>Don’t retrieve bad chunks just to hit your k target. If nothing in your knowledge base is actually relevant to the query, it&#39;s better to return nothing than to return vaguely-related content that confuses the model.</p><pre>retriever = vectorstore.as_retriever(<br>    search_type=&quot;similarity_score_threshold&quot;,<br>    search_kwargs={<br>        &quot;score_threshold&quot;: 0.7,  # Only return chunks above this similarity score<br>        &quot;k&quot;: 4<br>    }<br>)</pre><h3>Metadata Filtering</h3><p>Vector search finds semantically similar content, but sometimes you need to constrain <em>which documents</em> are even eligible — only search HR policies, or only search documents updated in the last 30 days, or only search content in English. This is where metadata filters come in.</p><pre>retriever = vectorstore.as_retriever(<br>    search_kwargs={<br>        &quot;k&quot;: 4,<br>        &quot;filter&quot;: {&quot;department&quot;: &quot;HR&quot;, &quot;document_type&quot;: &quot;policy&quot;}<br>        # Only consider chunks where metadata matches these conditions<br>    }<br>)</pre><h3>Multi-Query Retrieval</h3><p>One underrated technique: the user’s question, as phrased, might not be the best query for semantic search. <strong>Multi-query retrieval</strong> uses the LLM itself to generate multiple alternative phrasings of the question, runs all of them as separate queries, and takes the union of results. This catches relevant chunks that a single query might miss due to phrasing mismatches.</p><pre>from langchain.retrievers import MultiQueryRetriever<br>from langchain_openai import ChatOpenAI</pre><pre>llm = ChatOpenAI(temperature=0)</pre><pre>multi_retriever = MultiQueryRetriever.from_llm(<br>    retriever=vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 3}),<br>    llm=llm<br>    # Under the hood: generates 3-5 alternative phrasings of the query,<br>    # retrieves for each, deduplicates results<br>)</pre><h3>Chapter 7: Putting It All Together — A Working RAG Chain</h3><p>Here’s a complete, minimal, working RAG chain using LangChain’s modern interface. This is the skeleton of nearly every document Q&amp;A system you’ll ever build.</p><pre>from langchain_openai import ChatOpenAI, OpenAIEmbeddings<br>from langchain_community.vectorstores import FAISS<br>from langchain_community.document_loaders import PyPDFLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.prompts import ChatPromptTemplate<br>from langchain_core.runnables import RunnablePassthrough<br>from langchain_core.output_parsers import StrOutputParser</pre><pre># ─── PHASE 1: INDEXING (run once, offline) ───────────────────────────────────</pre><pre># 1. Load documents<br>loader = PyPDFLoader(&quot;company_handbook.pdf&quot;)<br>raw_docs = loader.load()</pre><pre># 2. Split into chunks<br>splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)<br>chunks = splitter.split_documents(raw_docs)</pre><pre># 3. Embed and store<br>embeddings = OpenAIEmbeddings()<br>vectorstore = FAISS.from_documents(chunks, embeddings)<br>vectorstore.save_local(&quot;handbook_index&quot;)</pre><pre># ─── PHASE 2: RETRIEVAL + GENERATION (runs per query) ────────────────────────</pre><pre># Load the pre-built index (skip re-embedding)<br>vectorstore = FAISS.load_local(&quot;handbook_index&quot;, embeddings,<br>                                allow_dangerous_deserialization=True)</pre><pre>retriever = vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 4})</pre><pre># The prompt that instructs the model to answer ONLY from retrieved context<br>rag_prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;,<br>     &quot;You are a helpful assistant answering questions about company policy. &quot;<br>     &quot;Use ONLY the following retrieved context to answer the question. &quot;<br>     &quot;If the answer is not in the context, say: &#39;I don&#39;t have that information.&#39; &quot;<br>     &quot;Do not use any knowledge outside of what&#39;s provided below.\n\n&quot;<br>     &quot;Context:\n{context}&quot;),<br>    (&quot;user&quot;, &quot;{question}&quot;)<br>])</pre><pre>llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0)  # temp=0 for consistent, factual answers</pre><pre>def format_docs(docs):<br>    # Combine retrieved chunks into a single context string<br>    return &quot;\n\n&quot;.join(<br>        f&quot;[Source: {doc.metadata.get(&#39;source&#39;, &#39;unknown&#39;)}, &quot;<br>        f&quot;Page: {doc.metadata.get(&#39;page&#39;, &#39;?&#39;)}]\n{doc.page_content}&quot;<br>        for doc in docs<br>    )</pre><pre># Build the chain using LangChain Expression Language (LCEL)<br>rag_chain = (<br>    {<br>        &quot;context&quot;: retriever | format_docs,  # retrieve → format as string<br>        &quot;question&quot;: RunnablePassthrough()    # pass question through unchanged<br>    }<br>    | rag_prompt         # fill the template<br>    | llm                # call the model<br>    | StrOutputParser()  # parse response to plain string<br>)</pre><pre># Use it<br>response = rag_chain.invoke(&quot;What is the reimbursement limit for travel expenses?&quot;) print(response)<br># &quot;According to the handbook, the travel reimbursement limit is $350 per night<br>#  for hotels and $75 per day for meals...&quot;</pre><p>This chain is clean, auditable, and straightforward to swap out individual pieces — change the loader, the splitter settings, the retriever strategy, or the underlying LLM without touching the rest of the pipeline.</p><h3>Chapter 8: Where RAG Breaks and How to Diagnose It</h3><p>RAG systems fail in consistent, diagnosable ways. Knowing the failure modes ahead of time saves days of debugging.</p><p><strong>“The model ignores the retrieved context and makes things up anyway.”</strong> Your system prompt isn’t firm enough. Add explicit grounding instructions: “Answer only from the context below. If the answer is not in the context, say so.” Setting temperature=0<br>on the LLM also helps with consistency.</p><p><strong>“Retrieval returns irrelevant chunks.”</strong><br>This is the most common failure, and it almost always traces to chunking. Chunks are too large (low retrieval precision), too small (not enough context per chunk), or split at bad boundaries (sentences split mid-idea). Try smaller chunks, increase overlap, or switch to a structure-aware splitter (markdown header, code-aware).</p><p><strong>“The right information is in the document but retrieval never finds it.”</strong> Your query phrasing and your document phrasing are too semantically distant. Try the multi-query retriever to cast a wider net. Also check: was this section actually indexed? Loaders silently fail on scanned PDFs, complex tables, and certain layouts.</p><p><strong>“The model’s answer is correct but I can’t trace where it came from.”</strong> Always include source metadata in your formatted context and instruct the model to cite it. Without attribution, RAG is a black box — with attribution, it’s auditable.</p><p><strong>“It works in testing but gives bad answers on long documents at scale.”</strong> Your k value (number of retrieved chunks) is hitting the LLM&#39;s context window limit. Either reduce k, reduce chunk size, or use a model with a larger context window. Also check for embedding model mismatch — if you indexed with one embedding model and query with another, the vector space is incompatible.</p><h3>Where This Takes You Next</h3><p>You now have a mental model of the complete RAG pipeline from ingestion to response — not just what the pieces are called, but <em>why</em> each one exists and what breaks when it’s wrong.</p><p>The natural next step is building something real with this. Start with a single clean PDF and a handful of test questions whose correct answers you already know. Run the full pipeline, check whether your retriever surfaces the right chunks for each question, then tune chunk size and overlap until retrieval quality is solid. Get that working before touching retriever strategies or advanced techniques.</p><p>Once retrieval is reliable, the rest — getting the model to answer well, adding conversation memory, citing sources — falls into place quickly. The retrieval quality is the foundation. Everything else is downstream from it.</p><p>RAG isn’t magic. It’s plumbing — well-designed plumbing that lets a language model answer questions about your actual data instead of guessing. Build the plumbing carefully, and the magic takes care of itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b89708c4406" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS in Angular — Chapter 10 (Final) | Real-World Patterns, Best Practices & Everything That…]]></title>
            <link>https://medium.com/@jackpritomsoren/rxjs-in-angular-chapter-10-final-real-world-patterns-best-practices-everything-that-9108710f10cd?source=rss-17ac2beef113------2</link>
            <guid isPermaLink="false">https://medium.com/p/9108710f10cd</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Jack Pritom Soren]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 07:43:20 GMT</pubDate>
            <atom:updated>2026-07-15T07:43:20.116Z</atom:updated>
            <content:encoded><![CDATA[<h3>RxJS in Angular — Chapter 10 (Final) | Real-World Patterns, Best Practices &amp; Everything That Actually Matters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVc4KR774sS-nW26NPLu-w.jpeg" /></figure><h3>👋 Welcome to the Final Chapter!</h3><p>You’ve made it. 🎉</p><p>Over the past 9 chapters, you’ve learned Observables, subscribe, pipe, map, filter, tap, switchMap, mergeMap, concatMap, Subject, BehaviorSubject, error handling, combining operators, forms, and timing operators.</p><p>Now let’s put it ALL together. This chapter is about <strong>real patterns you’ll use every single day</strong> in production Angular apps — and the mistakes you must avoid.</p><h3>🏗️ Pattern 1: The State Service Pattern (Mini State Management)</h3><p>In large Angular apps, managing shared state is the biggest challenge. You don’t always need NgRx — a simple service with BehaviorSubject is often enough.</p><h3>The Pattern</h3><pre>// feature-state.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { BehaviorSubject, Observable } from &#39;rxjs&#39;;<br>import { map } from &#39;rxjs/operators&#39;;</pre><pre>// Define the shape of your state<br>interface ProductState {<br>  products: Product[];<br>  selectedProduct: Product | null;<br>  isLoading: boolean;<br>  error: string | null;<br>  filters: {<br>    category: string;<br>    maxPrice: number;<br>    searchTerm: string;<br>  };<br>}</pre><pre>// Initial state<br>const initialState: ProductState = {<br>  products: [],<br>  selectedProduct: null,<br>  isLoading: false,<br>  error: null,<br>  filters: {<br>    category: &#39;all&#39;,<br>    maxPrice: 999999,<br>    searchTerm: &#39;&#39;<br>  }<br>};</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class ProductStateService {</pre><pre>  // The one source of truth<br>  private state$ = new BehaviorSubject&lt;ProductState&gt;(initialState);</pre><pre>  // Derived selectors — computed from state<br>  products$ = this.state$.pipe(map(s =&gt; s.products));<br>  selectedProduct$ = this.state$.pipe(map(s =&gt; s.selectedProduct));<br>  isLoading$ = this.state$.pipe(map(s =&gt; s.isLoading));<br>  error$ = this.state$.pipe(map(s =&gt; s.error));</pre><pre>  // Filtered products — automatically recomputes when state changes<br>  filteredProducts$ = this.state$.pipe(<br>    map(state =&gt; {<br>      return state.products<br>        .filter(p =&gt;<br>          (state.filters.category === &#39;all&#39; || p.category === state.filters.category) &amp;&amp;<br>          p.price &lt;= state.filters.maxPrice &amp;&amp;<br>          p.name.toLowerCase().includes(state.filters.searchTerm.toLowerCase())<br>        );<br>    })<br>  );</pre><pre>  // State updaters — the only way to change state<br>  setLoading(isLoading: boolean): void {<br>    this.updateState({ isLoading });<br>  }</pre><pre>  setProducts(products: Product[]): void {<br>    this.updateState({ products, isLoading: false, error: null });<br>  }</pre><pre>  setError(error: string): void {<br>    this.updateState({ error, isLoading: false });<br>  }</pre><pre>  selectProduct(product: Product | null): void {<br>    this.updateState({ selectedProduct: product });<br>  }</pre><pre>  updateFilters(filters: Partial&lt;ProductState[&#39;filters&#39;]&gt;): void {<br>    const currentFilters = this.state$.value.filters;<br>    this.updateState({ filters: { ...currentFilters, ...filters } });<br>  }</pre><pre>  // Private helper — immutable state update<br>  private updateState(partialState: Partial&lt;ProductState&gt;): void {<br>    this.state$.next({<br>      ...this.state$.value,<br>      ...partialState<br>    });<br>  }</pre><pre>  // Synchronous getter for imperative code<br>  get currentState(): ProductState {<br>    return this.state$.value;<br>  }<br>}</pre><h3>Using the State Service in Components</h3><pre>// product-list.component.ts<br>@Component({<br>  template: `<br>    &lt;div *ngIf=&quot;state.isLoading$ | async&quot;&gt;Loading... ⏳&lt;/div&gt;<br>    &lt;div *ngIf=&quot;state.error$ | async as err&quot; class=&quot;error&quot;&gt;{{ err }}&lt;/div&gt;</pre><pre>    &lt;div *ngFor=&quot;let product of state.filteredProducts$ | async&quot;&gt;<br>      &lt;h3&gt;{{ product.name }}&lt;/h3&gt;<br>      &lt;button (click)=&quot;state.selectProduct(product)&quot;&gt;View&lt;/button&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class ProductListComponent implements OnInit {</pre><pre>  constructor(<br>    public state: ProductStateService,<br>    private productService: ProductService<br>  ) {}</pre><pre>  ngOnInit(): void {<br>    this.state.setLoading(true);</pre><pre>    this.productService.getAll().subscribe({<br>      next: products =&gt; this.state.setProducts(products),<br>      error: err =&gt; this.state.setError(err.message)<br>    });<br>  }<br>}</pre><pre>// filter-bar.component.ts<br>@Component({<br>  template: `<br>    &lt;input<br>      [formControl]=&quot;search&quot;<br>      placeholder=&quot;Search...&quot;&gt;</pre><pre>    &lt;select [formControl]=&quot;category&quot;&gt;<br>      &lt;option value=&quot;all&quot;&gt;All&lt;/option&gt;<br>      &lt;option value=&quot;electronics&quot;&gt;Electronics&lt;/option&gt;<br>      &lt;option value=&quot;clothing&quot;&gt;Clothing&lt;/option&gt;<br>    &lt;/select&gt;<br>  `<br>})<br>export class FilterBarComponent implements OnInit, OnDestroy {</pre><pre>  search = new FormControl(&#39;&#39;);<br>  category = new FormControl(&#39;all&#39;);</pre><pre>  private destroy$ = new Subject&lt;void&gt;();</pre><pre>  constructor(private state: ProductStateService) {}</pre><pre>  ngOnInit(): void {<br>    this.search.valueChanges<br>      .pipe(debounceTime(300), takeUntil(this.destroy$))<br>      .subscribe(term =&gt; this.state.updateFilters({ searchTerm: term || &#39;&#39; }));</pre><pre>    this.category.valueChanges<br>      .pipe(takeUntil(this.destroy$))<br>      .subscribe(cat =&gt; this.state.updateFilters({ category: cat || &#39;all&#39; }));<br>  }</pre><pre>  ngOnDestroy(): void {<br>    this.destroy$.next();<br>    this.destroy$.complete();<br>  }<br>}</pre><p>The filter component and the list component are completely decoupled — they communicate through the state service! 🎯</p><h3>🏗️ Pattern 2: The Smart/Dumb Component Pattern</h3><p><strong>Smart components</strong> manage data and subscriptions.<br><strong>Dumb components</strong> just display data via @Input and emit events via @Output.</p><pre>// SMART component — manages data<br>@Component({<br>  selector: &#39;app-users-page&#39;,<br>  template: `<br>    &lt;!-- Pass data DOWN to dumb component via @Input --&gt;<br>    &lt;app-user-list<br>      [users]=&quot;users$ | async&quot;<br>      [isLoading]=&quot;isLoading$ | async&quot;<br>      (userSelected)=&quot;onUserSelected($event)&quot;<br>      (deleteRequested)=&quot;onDeleteUser($event)&quot;&gt;<br>    &lt;/app-user-list&gt;<br>  `<br>})<br>export class UsersPageComponent {<br>  users$ = this.userService.getUsers();<br>  isLoading$ = new BehaviorSubject(true);</pre><pre>  constructor(private userService: UserService) {<br>    this.users$.subscribe(() =&gt; this.isLoading$.next(false));<br>  }</pre><pre>  onUserSelected(user: User): void { ... }<br>  onDeleteUser(userId: number): void { ... }<br>}</pre><pre>// DUMB component — only displays, zero knowledge of services<br>@Component({<br>  selector: &#39;app-user-list&#39;,<br>  template: `<br>    &lt;div *ngIf=&quot;isLoading&quot;&gt;Loading...&lt;/div&gt;<br>    &lt;div *ngFor=&quot;let user of users&quot;&gt;<br>      {{ user.name }}<br>      &lt;button (click)=&quot;userSelected.emit(user)&quot;&gt;View&lt;/button&gt;<br>      &lt;button (click)=&quot;deleteRequested.emit(user.id)&quot;&gt;Delete&lt;/button&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class UserListComponent {<br>  @Input() users: User[] | null = [];<br>  @Input() isLoading: boolean | null = false;<br>  @Output() userSelected = new EventEmitter&lt;User&gt;();<br>  @Output() deleteRequested = new EventEmitter&lt;number&gt;();<br>}</pre><p>Dumb components are easy to test, reuse, and understand! 💡</p><h3>🏗️ Pattern 3: The Loading/Error/Success State Pattern</h3><p>Every page that fetches data should handle 3 states. Here’s the cleanest way:</p><pre>// Shared types<br>interface AsyncState&lt;T&gt; {<br>  data: T | null;<br>  isLoading: boolean;<br>  error: string | null;<br>}</pre><pre>// Helper function<br>function createLoadingState&lt;T&gt;(): AsyncState&lt;T&gt; {<br>  return { data: null, isLoading: true, error: null };<br>}</pre><pre>// In your component<br>@Component({<br>  template: `<br>    &lt;ng-container *ngIf=&quot;state$ | async as s&quot;&gt;</pre><pre>      &lt;app-skeleton *ngIf=&quot;s.isLoading&quot;&gt;&lt;/app-skeleton&gt;</pre><pre>      &lt;app-error-message<br>        *ngIf=&quot;s.error&quot;<br>        [message]=&quot;s.error&quot;<br>        (retry)=&quot;load()&quot;&gt;<br>      &lt;/app-error-message&gt;</pre><pre>      &lt;app-product-grid<br>        *ngIf=&quot;s.data &amp;&amp; !s.isLoading&quot;<br>        [products]=&quot;s.data&quot;&gt;<br>      &lt;/app-product-grid&gt;</pre><pre>    &lt;/ng-container&gt;<br>  `<br>})<br>export class ProductPageComponent implements OnInit {</pre><pre>  state$!: Observable&lt;AsyncState&lt;Product[]&gt;&gt;;</pre><pre>  constructor(private productService: ProductService) {}</pre><pre>  ngOnInit(): void {<br>    this.load();<br>  }</pre><pre>  load(): void {<br>    this.state$ = this.productService.getProducts().pipe(<br>      map(products =&gt; ({ data: products, isLoading: false, error: null })),<br>      catchError(err =&gt; of({ data: null, isLoading: false, error: err.message })),<br>      startWith(createLoadingState&lt;Product[]&gt;())<br>    );<br>  }<br>}</pre><h3>🛑 The Top 10 RxJS Mistakes to Avoid</h3><h3>Mistake 1: Not Unsubscribing</h3><pre>// ❌ Memory leak!<br>ngOnInit() {<br>  interval(1000).subscribe(n =&gt; console.log(n));<br>}</pre><pre>// ✅ Proper cleanup<br>ngOnInit() {<br>  interval(1000)<br>    .pipe(takeUntil(this.destroy$))<br>    .subscribe(n =&gt; console.log(n));<br>}</pre><h3>Mistake 2: Nested Subscribes</h3><pre>// ❌ Never do this — nested subscribes!<br>this.route.params.subscribe(params =&gt; {<br>  this.userService.getUser(params[&#39;id&#39;]).subscribe(user =&gt; {<br>    this.user = user;<br>  });<br>});</pre><pre>// ✅ Use switchMap<br>this.route.params.pipe(<br>  switchMap(params =&gt; this.userService.getUser(params[&#39;id&#39;]))<br>).subscribe(user =&gt; this.user = user);</pre><h3>Mistake 3: Subscribing in Services</h3><pre>// ❌ Bad — subscribing in service creates untraceable subscriptions<br>@Injectable()<br>export class UserService {<br>  loadUsers() {<br>    this.http.get(&#39;/api/users&#39;).subscribe(users =&gt; {<br>      this.users = users; // Mutating service state in subscribe!<br>    });<br>  }<br>}</pre><pre>// ✅ Good — return the Observable, let the component decide<br>@Injectable()<br>export class UserService {<br>  getUsers(): Observable&lt;User[]&gt; {<br>    return this.http.get&lt;User[]&gt;(&#39;/api/users&#39;);<br>  }<br>}</pre><h3>Mistake 4: Forgetting startWith in combineLatest</h3><pre>// ❌ combineLatest won&#39;t emit until ALL observables have emitted at least once<br>combineLatest([<br>  this.searchControl.valueChanges,  // Won&#39;t emit until user types!<br>  this.categoryControl.valueChanges<br>])</pre><pre>// ✅ Use startWith so combineLatest fires immediately<br>combineLatest([<br>  this.searchControl.valueChanges.pipe(startWith(&#39;&#39;)),<br>  this.categoryControl.valueChanges.pipe(startWith(&#39;all&#39;))<br>])</pre><h3>Mistake 5: Using switchMap When You Should Use mergeMap</h3><pre>// ❌ Wrong — switchMap cancels previous file uploads!<br>from(files).pipe(<br>  switchMap(file =&gt; this.upload(file))  // Each new file cancels the previous upload!<br>)</pre><pre>// ✅ Correct — mergeMap runs all uploads in parallel<br>from(files).pipe(<br>  mergeMap(file =&gt; this.upload(file))<br>)</pre><h3>Mistake 6: Not Handling Errors</h3><pre>// ❌ If API fails, the entire Observable dies — no recovery<br>this.http.get(&#39;/api/data&#39;).subscribe(data =&gt; this.data = data);</pre><pre>// ✅ Always catch errors<br>this.http.get(&#39;/api/data&#39;).pipe(<br>  catchError(err =&gt; {<br>    this.error = &#39;Failed to load&#39;;<br>    return of([]);<br>  })<br>).subscribe(data =&gt; this.data = data);</pre><h3>Mistake 7: Overcomplicating Simple Things</h3><pre>// ❌ Too complex for a simple HTTP call<br>this.http.get(&#39;/api/users&#39;).pipe(<br>  take(1),  // Not needed — HTTP already completes after one emission<br>  first(),  // Also not needed<br>  shareReplay(1)  // Also unnecessary for a one-time load<br>)</pre><pre>// ✅ Keep it simple<br>this.http.get(&#39;/api/users&#39;)</pre><h3>Mistake 8: Not Using async Pipe</h3><pre>// ❌ Manual subscribe = manual unsubscribe burden<br>ngOnInit() {<br>  this.userService.getUsers().subscribe(users =&gt; this.users = users);<br>}</pre><pre>// ✅ async pipe handles everything<br>users$ = this.userService.getUsers();<br>// Template: *ngFor=&quot;let user of users$ | async&quot;</pre><h3>Mistake 9: Exposing Subject Directly</h3><pre>// ❌ Any component can push values — breaks encapsulation!<br>cartItems$ = new BehaviorSubject&lt;CartItem[]&gt;([]);</pre><pre>// ✅ Private subject, public Observable<br>private cartItemsSubject = new BehaviorSubject&lt;CartItem[]&gt;([]);<br>cartItems$ = this.cartItemsSubject.asObservable();</pre><h3>Mistake 10: Using tap to Extract Data</h3><pre>// ❌ tap should not be used to extract values like this<br>let userData: User;<br>this.getUser().pipe(<br>  tap(user =&gt; userData = user)  // Side effect to extract — bad pattern!<br>).subscribe();</pre><pre>// ✅ Use the data in subscribe or map<br>this.getUser().subscribe(user =&gt; {<br>  this.userData = user;<br>});</pre><h3>📋 The Complete RxJS Cheat Sheet</h3><p><strong>Creating Observables</strong></p><ul><li>of(1,2,3) — from static values</li><li>from([1,2,3]) — from array or Promise</li><li>interval(ms) — ticks every N ms</li><li>timer(ms) — emits once after delay</li><li>fromEvent(el, &#39;click&#39;) — from DOM event</li><li>new Observable(observer =&gt; ...) — custom</li></ul><p><strong>Transforming</strong></p><ul><li>map(fn) — transform each value</li><li>filter(fn) — keep only matching values</li><li>tap(fn) — side effects, no change</li></ul><p><strong>Flattening (Observables of Observables)</strong></p><ul><li>switchMap(fn) — cancel old, start new (search, route)</li><li>mergeMap(fn) — run all in parallel (uploads)</li><li>concatMap(fn) — run one at a time (sequential)</li></ul><p><strong>Timing</strong></p><ul><li>debounceTime(ms) — wait for silence (search box)</li><li>throttleTime(ms) — limit rate (scroll events)</li><li>distinctUntilChanged() — skip duplicates</li><li>take(n) — take first N, then complete</li><li>takeUntil(obs$) — take until signal</li></ul><p><strong>Combining</strong></p><ul><li>forkJoin({...}) — parallel, wait for all</li><li>combineLatest([...]) — emit on any change</li><li>withLatestFrom(obs$) — snapshot on trigger</li><li>zip(obs1, obs2) — pair by position</li></ul><p><strong>Error Handling</strong></p><ul><li>catchError(fn) — catch and recover</li><li>retry(n) — retry N times</li><li>finalize(fn) — always runs last</li></ul><p><strong>Subjects</strong></p><ul><li>Subject — multicast, no memory</li><li>BehaviorSubject(init) — remembers latest</li><li>ReplaySubject(n) — remembers last N</li></ul><h3>🎓 Your Journey So Far — The Complete Series</h3><p>Here’s everything you’ve learned across all 10 chapters:</p><p><strong>Chapter 1</strong> — Observables: the data stream<br><strong>Chapter 2</strong> — Subscribe &amp; unsubscribe: open and close the tap<br><strong>Chapter 3</strong> — pipe, map, filter, tap: transform your data<br><strong>Chapter 4</strong> — switchMap, mergeMap, concatMap: handle nested streams<br><strong>Chapter 5</strong> — Subject &amp; BehaviorSubject: broadcast to many<br><strong>Chapter 6</strong> — Error handling: catchError, retry, finalize<br><strong>Chapter 7</strong> — forkJoin, combineLatest: combine multiple streams<br><strong>Chapter 8</strong> — Reactive Forms + RxJS: live validation and dynamic forms<br><strong>Chapter 9</strong> — Timing operators: debounceTime, throttleTime, interval<br><strong>Chapter 10</strong> — Real-world patterns and best practices (this chapter!)</p><h3>🚀 What to Learn Next</h3><p>You’re no longer a beginner! Here’s your roadmap to RxJS mastery:</p><p><strong>1. NgRx</strong> — Formal state management built on RxJS (for very large apps)</p><p><strong>2. Angular Signals</strong> — Angular’s newer reactivity system (complements RxJS)</p><p><strong>3. shareReplay()</strong> — Share a single HTTP response between multiple subscribers</p><p><strong>4. Custom Operators</strong> — Build your own reusable operators</p><p><strong>5. Testing RxJS</strong> — Use TestScheduler and marble testing</p><p><strong>6. RxJS in Node.js</strong> — Use the same patterns on the backend</p><h3>💌 Thank You for Reading!</h3><p>You’ve completed the entire <strong>RxJS in Angular Deep Dive</strong> series.</p><p>Remember: RxJS seems complex at first, but once you see the patterns — Observable → pipe → subscribe, BehaviorSubject in services, async pipe in templates — everything clicks.</p><p>The best way to get better is to <strong>build</strong>. Take a real project and apply what you’ve learned here.</p><p>Good luck, and happy coding! 🚀</p><p><em>💌 RxJS Deep Dive Newsletter Series | Chapter 10 of 10 — The Final Chapter</em></p><p><em>Share this series with your team! Every Angular developer needs to understand RxJS.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9108710f10cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS in Angular — Chapter 9 | Timing Operators — debounceTime, throttleTime, interval & More]]></title>
            <link>https://medium.com/@jackpritomsoren/rxjs-in-angular-chapter-9-timing-operators-debouncetime-throttletime-interval-more-0e4d3e47721e?source=rss-17ac2beef113------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e4d3e47721e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jack Pritom Soren]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 06:55:35 GMT</pubDate>
            <atom:updated>2026-07-10T06:55:35.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NolP6y0fKvsY6QbzBbtsRA.jpeg" /></figure><h3>👋 Welcome to Chapter 9!</h3><p>Imagine a user typing in a search box. They type “i”, “ip”, “iph”, “ipho”, “iphon”, “iphone” — 6 keystrokes in 2 seconds.</p><p>Do you really want to make <strong>6 API calls</strong>? Of course not! You want to wait until they stop typing and then search once.</p><p>That’s what <strong>timing operators</strong> solve. They control <strong>when</strong> and <strong>how often</strong> values flow through your stream.</p><h3>⏱️ debounceTime() — Wait for the Silence</h3><p>debounceTime(ms) waits until there&#39;s a pause of ms milliseconds, THEN lets the latest value through.</p><p>Think of it like this: “Ignore everything until they stop for a moment.”</p><p>Like a person who waits for you to finish talking before responding.</p><pre>import { debounceTime } from &#39;rxjs/operators&#39;;</pre><pre>// User types fast: &#39;i&#39; → &#39;ip&#39; → &#39;iph&#39; → &#39;ipho&#39; → &#39;iphon&#39; → &#39;iphone&#39;<br>// debounceTime(400) waits 400ms of silence, then sends &#39;iphone&#39; only<br>searchControl.valueChanges<br>  .pipe(debounceTime(400))<br>  .subscribe(term =&gt; {<br>    this.searchProducts(term);  // Only called ONCE with &#39;iphone&#39;!<br>  });</pre><h3>Timeline:</h3><pre>Type &#39;i&#39;     →  [400ms timer starts]<br>Type &#39;ip&#39;    →  [reset timer]<br>Type &#39;iph&#39;   →  [reset timer]<br>Type &#39;iphone&#39;→  [reset timer]<br>... 400ms silence ...<br>EMIT: &#39;iphone&#39; ✅</pre><h3>Real Angular Example — Smart Search Box</h3><pre>import { Component, OnInit, OnDestroy } from &#39;@angular/core&#39;;<br>import { FormControl } from &#39;@angular/forms&#39;;<br>import { Observable, Subject } from &#39;rxjs&#39;;<br>import { debounceTime, distinctUntilChanged, switchMap, startWith, takeUntil } from &#39;rxjs/operators&#39;;</pre><pre>@Component({<br>  selector: &#39;app-search-box&#39;,<br>  template: `<br>    &lt;div class=&quot;search-wrapper&quot;&gt;<br>      &lt;input<br>        [formControl]=&quot;searchControl&quot;<br>        placeholder=&quot;Search products...&quot;<br>        (keyup.escape)=&quot;clearSearch()&quot;&gt;</pre><pre>      &lt;span *ngIf=&quot;isLoading&quot; class=&quot;spinner&quot;&gt;🔄&lt;/span&gt;<br>      &lt;button *ngIf=&quot;searchControl.value&quot; (click)=&quot;clearSearch()&quot;&gt;✕&lt;/button&gt;<br>    &lt;/div&gt;</pre><pre>    &lt;div class=&quot;results-count&quot; *ngIf=&quot;(results$ | async) as results&quot;&gt;<br>      Found {{ results.length }} results<br>    &lt;/div&gt;</pre><pre>    &lt;div class=&quot;results&quot;&gt;<br>      &lt;div *ngFor=&quot;let item of results$ | async&quot; class=&quot;result-item&quot;&gt;<br>        &lt;strong&gt;{{ item.name }}&lt;/strong&gt;<br>        &lt;span&gt;৳{{ item.price }}&lt;/span&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class SearchBoxComponent implements OnInit, OnDestroy {</pre><pre>  searchControl = new FormControl(&#39;&#39;);<br>  results$!: Observable&lt;Product[]&gt;;<br>  isLoading = false;</pre><pre>  private destroy$ = new Subject&lt;void&gt;();</pre><pre>  constructor(private productService: ProductService) {}</pre><pre>  ngOnInit(): void {<br>    this.results$ = this.searchControl.valueChanges.pipe(<br>      startWith(&#39;&#39;),<br>      debounceTime(400),           // Wait 400ms after typing stops<br>      distinctUntilChanged(),      // Don&#39;t search if value is the same<br>      tap(() =&gt; this.isLoading = true),<br>      switchMap(term =&gt;<br>        this.productService.search(term || &#39;&#39;).pipe(<br>          catchError(() =&gt; of([]))<br>        )<br>      ),<br>      tap(() =&gt; this.isLoading = false),<br>      takeUntil(this.destroy$)<br>    );<br>  }</pre><pre>  clearSearch(): void {<br>    this.searchControl.setValue(&#39;&#39;);<br>  }</pre><pre>  ngOnDestroy(): void {<br>    this.destroy$.next();<br>    this.destroy$.complete();<br>  }<br>}</pre><p>Without debounceTime, a user typing &quot;iphone 14&quot; (8 keystrokes) would make <strong>8 API calls</strong>. With it: <strong>1 call</strong>. 🎉</p><h3>⚡ throttleTime() — Only Once Per Time Window</h3><p>throttleTime(ms) lets the FIRST value through, then ignores everything for ms milliseconds.</p><p>“One value per window — take the first, ignore the rest.”</p><p>Like a bouncer who lets one person in, then waits before letting the next.</p><pre>import { throttleTime } from &#39;rxjs/operators&#39;;<br>import { fromEvent } from &#39;rxjs&#39;;</pre><pre>// User scrolls constantly — fire only once every 200ms<br>fromEvent(window, &#39;scroll&#39;)<br>  .pipe(throttleTime(200))<br>  .subscribe(() =&gt; {<br>    this.checkIfNearBottom();<br>  });</pre><h3>debounceTime vs throttleTime:</h3><pre>User clicks rapidly: click, click, click, click, click<br>                     (every 100ms)</pre><pre>debounceTime(300):   ................ EMIT (only after 300ms silence)<br>throttleTime(300):   EMIT ............. EMIT (first click, then every 300ms)</pre><p>Use <strong>debounceTime</strong> when you want to wait for the user to FINISH (search, form input)<br>Use <strong>throttleTime</strong> when you want regular updates while something is happening (scroll, resize, mouse move)</p><h3>🎯 distinctUntilChanged() — Skip Identical Values</h3><p>This one is simple: don’t emit if the value is the same as the last one.</p><pre>import { distinctUntilChanged } from &#39;rxjs/operators&#39;;</pre><pre>// User clicks in the same input field without changing value<br>searchControl.valueChanges<br>  .pipe(<br>    debounceTime(400),<br>    distinctUntilChanged()  // Don&#39;t search again if value didn&#39;t change!<br>  )<br>  .subscribe(term =&gt; this.search(term));</pre><p>You can also compare objects with a custom comparator:</p><pre>this.filterForm.valueChanges.pipe(<br>  debounceTime(300),<br>  distinctUntilChanged((prev, curr) =&gt;<br>    prev.category === curr.category &amp;&amp; prev.maxPrice === curr.maxPrice<br>  )<br>)</pre><h3>🕐 interval() — Emit on a Schedule</h3><p>interval(ms) emits incrementing numbers (0, 1, 2, 3...) every ms milliseconds. It runs <strong>forever</strong> until you unsubscribe.</p><pre>import { interval } from &#39;rxjs&#39;;<br>import { takeUntil, take } from &#39;rxjs/operators&#39;;</pre><pre>// Emit every 1 second: 0, 1, 2, 3...<br>interval(1000).subscribe(n =&gt; console.log(n));</pre><h3>Real Example — Auto-Refresh Dashboard</h3><pre>@Component({<br>  selector: &#39;app-live-dashboard&#39;,<br>  template: `<br>    &lt;div class=&quot;dashboard&quot;&gt;<br>      &lt;h2&gt;🔴 Live Orders&lt;/h2&gt;<br>      &lt;p class=&quot;last-updated&quot;&gt;Last updated: {{ lastUpdated | date:&#39;HH:mm:ss&#39; }}&lt;/p&gt;</pre><pre>      &lt;div *ngFor=&quot;let order of orders$ | async&quot; class=&quot;order-row&quot;&gt;<br>        #{{ order.id }} — {{ order.status }} — ৳{{ order.total }}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class LiveDashboardComponent implements OnInit, OnDestroy {</pre><pre>  orders$!: Observable&lt;Order[]&gt;;<br>  lastUpdated = new Date();</pre><pre>  private destroy$ = new Subject&lt;void&gt;();</pre><pre>  constructor(private orderService: OrderService) {}</pre><pre>  ngOnInit(): void {<br>    // Load immediately, then refresh every 30 seconds<br>    this.orders$ = interval(30000).pipe(<br>      startWith(0),  // Emit immediately (don&#39;t wait for first interval)<br>      switchMap(() =&gt; {<br>        this.lastUpdated = new Date();<br>        return this.orderService.getLiveOrders();<br>      }),<br>      takeUntil(this.destroy$)<br>    );<br>  }</pre><pre>  ngOnDestroy(): void {<br>    this.destroy$.next();<br>    this.destroy$.complete();<br>  }<br>}</pre><p>The dashboard refreshes every 30 seconds automatically — no manual button needed!</p><h3>⏲️ timer() — Emit Once After a Delay</h3><p>timer(delay) emits once after the specified delay.<br>timer(delay, interval) emits once after delay, then every interval.</p><pre>import { timer } from &#39;rxjs&#39;;</pre><pre>// Show a toast notification, then hide it after 3 seconds<br>this.showToast = true;</pre><pre>timer(3000).pipe(<br>  takeUntil(this.destroy$)<br>).subscribe(() =&gt; {<br>  this.showToast = false;<br>});</pre><h3>Real Example — Auto-dismiss Notifications</h3><pre>@Component({<br>  selector: &#39;app-toast&#39;,<br>  template: `<br>    &lt;div *ngFor=&quot;let toast of toasts&quot; class=&quot;toast&quot; [class]=&quot;toast.type&quot;&gt;<br>      {{ toast.message }}<br>      &lt;button (click)=&quot;dismiss(toast.id)&quot;&gt;✕&lt;/button&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class ToastComponent implements OnInit, OnDestroy {</pre><pre>  toasts: Toast[] = [];<br>  private destroy$ = new Subject&lt;void&gt;();</pre><pre>  constructor(private toastService: ToastService) {}</pre><pre>  ngOnInit(): void {<br>    this.toastService.toasts$<br>      .pipe(takeUntil(this.destroy$))<br>      .subscribe(toast =&gt; {<br>        this.toasts.push(toast);</pre><pre>        // Auto-remove after 4 seconds<br>        timer(4000)<br>          .pipe(takeUntil(this.destroy$))<br>          .subscribe(() =&gt; {<br>            this.dismiss(toast.id);<br>          });<br>      });<br>  }</pre><pre>  dismiss(id: number): void {<br>    this.toasts = this.toasts.filter(t =&gt; t.id !== id);<br>  }</pre><pre>  ngOnDestroy(): void {<br>    this.destroy$.next();<br>    this.destroy$.complete();<br>  }<br>}</pre><h3>📡 fromEvent() — Turn DOM Events into Observables</h3><p>fromEvent converts any DOM event into an Observable stream!</p><pre>import { fromEvent } from &#39;rxjs&#39;;<br>import { debounceTime, map } from &#39;rxjs/operators&#39;;</pre><pre>// Infinite scroll — detect when user is near bottom<br>const scroll$ = fromEvent(window, &#39;scroll&#39;).pipe(<br>  throttleTime(200),<br>  map(() =&gt; {<br>    const scrollTop = window.scrollY;<br>    const windowHeight = window.innerHeight;<br>    const docHeight = document.documentElement.scrollHeight;<br>    return (scrollTop + windowHeight) / docHeight * 100; // % scrolled<br>  }),<br>  filter(pct =&gt; pct &gt; 80)  // Only when 80% scrolled<br>);</pre><pre>scroll$.pipe(<br>  takeUntil(this.destroy$)<br>).subscribe(() =&gt; {<br>  this.loadMoreItems();<br>});</pre><h3>🏗️ Full Real-World Example — Infinite Scroll List</h3><pre>@Component({<br>  selector: &#39;app-infinite-list&#39;,<br>  template: `<br>    &lt;div class=&quot;scroll-container&quot; #scrollContainer&gt;<br>      &lt;div *ngFor=&quot;let item of items&quot; class=&quot;list-item&quot;&gt;<br>        &lt;strong&gt;{{ item.title }}&lt;/strong&gt;<br>        &lt;p&gt;{{ item.body }}&lt;/p&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;div *ngIf=&quot;isLoadingMore&quot; class=&quot;loading-more&quot;&gt;<br>        Loading more... ⏳<br>      &lt;/div&gt;</pre><pre>      &lt;div *ngIf=&quot;noMoreItems&quot; class=&quot;end-message&quot;&gt;<br>        🏁 You&#39;ve reached the end!<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class InfiniteListComponent implements OnInit, OnDestroy {</pre><pre>  items: Item[] = [];<br>  currentPage = 1;<br>  isLoadingMore = false;<br>  noMoreItems = false;</pre><pre>  private destroy$ = new Subject&lt;void&gt;();</pre><pre>  constructor(<br>    private itemService: ItemService,<br>    private el: ElementRef<br>  ) {}</pre><pre>  ngOnInit(): void {<br>    // Load initial items<br>    this.loadPage(1);</pre><pre>    // Watch for scroll near bottom<br>    fromEvent(this.el.nativeElement.querySelector(&#39;.scroll-container&#39;), &#39;scroll&#39;)<br>      .pipe(<br>        throttleTime(300),<br>        filter(() =&gt; !this.isLoadingMore &amp;&amp; !this.noMoreItems),<br>        filter((event: any) =&gt; {<br>          const el = event.target;<br>          const nearBottom = el.scrollTop + el.clientHeight &gt;= el.scrollHeight - 200;<br>          return nearBottom;<br>        }),<br>        takeUntil(this.destroy$)<br>      )<br>      .subscribe(() =&gt; {<br>        this.currentPage++;<br>        this.loadPage(this.currentPage);<br>      });<br>  }</pre><pre>  private loadPage(page: number): void {<br>    this.isLoadingMore = true;</pre><pre>    this.itemService.getItems(page).subscribe({<br>      next: (newItems) =&gt; {<br>        if (newItems.length === 0) {<br>          this.noMoreItems = true;<br>        } else {<br>          this.items = [...this.items, ...newItems];<br>        }<br>        this.isLoadingMore = false;<br>      },<br>      error: () =&gt; {<br>        this.isLoadingMore = false;<br>      }<br>    });<br>  }</pre><pre>  ngOnDestroy(): void {<br>    this.destroy$.next();<br>    this.destroy$.complete();<br>  }<br>}</pre><h3>🧠 Quick Reference — When to Use Which</h3><p><strong>debounceTime(400)</strong> — User is typing in a search box. Wait for them to pause before searching.</p><p><strong>throttleTime(200)</strong> — User is scrolling or resizing. Handle events at most once per 200ms.</p><p><strong>distinctUntilChanged()</strong> — Don&#39;t trigger again if the value hasn&#39;t actually changed.</p><p><strong>interval(30000)</strong> — Refresh dashboard data every 30 seconds.</p><p><strong>timer(3000)</strong> — Auto-dismiss a notification after 3 seconds.</p><p><strong>fromEvent(el, &#39;scroll&#39;)</strong> — Convert a DOM scroll event into an Observable.</p><h3>🧠 Chapter 9 Summary — What You Learned</h3><ul><li><strong>debounceTime(ms)</strong> — emits only after the stream is silent for ms milliseconds. Best for search inputs.</li><li><strong>throttleTime(ms)</strong> — emits the first value, then ignores for ms milliseconds. Best for scroll/resize events.</li><li><strong>distinctUntilChanged()</strong> — skips emission if value is same as previous. Essential for search and forms.</li><li><strong>interval(ms)</strong> — emits 0, 1, 2... every ms milliseconds. Best for polling/auto-refresh.</li><li><strong>timer(ms)</strong> — emits once after delay. Best for auto-dismiss notifications.</li><li><strong>fromEvent(element, event)</strong> — turns any DOM event into an Observable. Best for scroll, click, resize.</li></ul><h3>📚 Coming Up in Chapter 10 — The Final Chapter!</h3><p>We wrap up the series with the <strong>most important real-world patterns</strong> every Angular developer should know:</p><ul><li>The <strong>async pipe + loading state</strong> pattern</li><li>The <strong>smart/dumb component</strong> pattern with Observables</li><li>The <strong>state management</strong> pattern using BehaviorSubject</li><li><strong>Performance tips</strong> — avoiding common RxJS pitfalls</li></ul><p>See you in the final chapter! 🚀</p><p><em>💌 RxJS Deep Dive Newsletter Series | Chapter 9 of 10</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e4d3e47721e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS in Angular — Chapter 8 | RxJS + Angular Reactive Forms — Live Validation ও Dynamic Forms]]></title>
            <link>https://medium.com/@jackpritomsoren/rxjs-in-angular-chapter-8-rxjs-angular-reactive-forms-live-validation-%E0%A6%93-dynamic-forms-93707ce58fd5?source=rss-17ac2beef113------2</link>
            <guid isPermaLink="false">https://medium.com/p/93707ce58fd5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Jack Pritom Soren]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 05:47:39 GMT</pubDate>
            <atom:updated>2026-07-04T05:47:39.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaCQuL1xGdX6M75u-9K4UQ.jpeg" /></figure><h3>“RxJS + Angular Reactive Forms — Live Validation &amp; Dynamic Forms”</h3><h3>👋 Welcome to Chapter 8!</h3><p>Forms are EVERYWHERE in web apps — login, registration, checkout, search, settings.</p><p>Angular’s <strong>Reactive Forms</strong> are powered by RxJS under the hood. Every FormControl has streams you can subscribe to — valueChanges, statusChanges. This unlocks incredibly powerful form behavior that would be painfully difficult to build any other way.</p><p>Today we build real, production-quality forms with RxJS superpowers!</p><h3>🎛️ The Reactive Forms Quick Setup</h3><p>First, let’s make sure we have the right setup:</p><h3>app.module.ts</h3><pre>import { ReactiveFormsModule } from &#39;@angular/forms&#39;;</pre><pre>@NgModule({<br>  imports: [ReactiveFormsModule]<br>})<br>export class AppModule {}</pre><h3>💡 The Key Streams on Every FormControl</h3><p>Every FormControl, FormGroup, and FormArray has two key Observable streams:</p><p><strong>valueChanges</strong> — emits every time the value changes<br><strong>statusChanges</strong> — emits every time the validation status changes (&#39;VALID&#39;, &#39;INVALID&#39;, &#39;PENDING&#39;, &#39;DISABLED&#39;)</p><pre>const emailControl = new FormControl(&#39;&#39;);</pre><pre>// Watch the value<br>emailControl.valueChanges.subscribe(value =&gt; {<br>  console.log(&#39;Email is now:&#39;, value);<br>});</pre><pre>// Watch the validation status<br>emailControl.statusChanges.subscribe(status =&gt; {<br>  console.log(&#39;Status:&#39;, status); // &#39;VALID&#39;, &#39;INVALID&#39;, &#39;PENDING&#39;, &#39;DISABLED&#39;<br>});</pre><h3>🔍 Real Example 1 — Live Username Availability Check</h3><p>This is extremely common: as the user types a username, check if it’s available.</p><pre>// register.component.ts<br>import { Component, OnInit, OnDestroy } from &#39;@angular/core&#39;;<br>import { FormBuilder, FormGroup, Validators, AbstractControl } from &#39;@angular/forms&#39;;<br>import { Subject } from &#39;rxjs&#39;;<br>import { debounceTime, distinctUntilChanged, switchMap, takeUntil } from &#39;rxjs/operators&#39;;</pre><pre>@Component({<br>  selector: &#39;app-register&#39;,<br>  template: `<br>    &lt;form [formGroup]=&quot;registerForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;</pre><pre>      &lt;div class=&quot;field&quot;&gt;<br>        &lt;label&gt;Username&lt;/label&gt;<br>        &lt;input formControlName=&quot;username&quot; placeholder=&quot;Choose a username&quot; /&gt;</pre><pre>        &lt;!-- Checking availability --&gt;<br>        &lt;span *ngIf=&quot;isCheckingUsername&quot; class=&quot;checking&quot;&gt;<br>          Checking availability... ⏳<br>        &lt;/span&gt;</pre><pre>        &lt;!-- Available --&gt;<br>        &lt;span *ngIf=&quot;usernameAvailable === true&quot; class=&quot;available&quot;&gt;<br>          ✅ Username is available!<br>        &lt;/span&gt;</pre><pre>        &lt;!-- Taken --&gt;<br>        &lt;span *ngIf=&quot;usernameAvailable === false&quot; class=&quot;taken&quot;&gt;<br>          ❌ Username is already taken<br>        &lt;/span&gt;</pre><pre>        &lt;!-- Validation errors --&gt;<br>        &lt;span *ngIf=&quot;registerForm.get(&#39;username&#39;)?.errors?.[&#39;required&#39;] &amp;&amp;<br>                     registerForm.get(&#39;username&#39;)?.touched&quot;&gt;<br>          Username is required<br>        &lt;/span&gt;<br>        &lt;span *ngIf=&quot;registerForm.get(&#39;username&#39;)?.errors?.[&#39;minlength&#39;]&quot;&gt;<br>          At least 3 characters required<br>        &lt;/span&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;div class=&quot;field&quot;&gt;<br>        &lt;label&gt;Email&lt;/label&gt;<br>        &lt;input formControlName=&quot;email&quot; type=&quot;email&quot; placeholder=&quot;Enter email&quot; /&gt;<br>        &lt;span *ngIf=&quot;registerForm.get(&#39;email&#39;)?.errors?.[&#39;email&#39;] &amp;&amp;<br>                     registerForm.get(&#39;email&#39;)?.touched&quot;&gt;<br>          Invalid email address<br>        &lt;/span&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;div class=&quot;field&quot;&gt;<br>        &lt;label&gt;Password&lt;/label&gt;<br>        &lt;input formControlName=&quot;password&quot; type=&quot;password&quot; placeholder=&quot;Password&quot; /&gt;<br>        &lt;div class=&quot;password-strength&quot; [class]=&quot;passwordStrength&quot;&gt;<br>          {{ passwordStrengthLabel }}<br>        &lt;/div&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;div class=&quot;field&quot;&gt;<br>        &lt;label&gt;Confirm Password&lt;/label&gt;<br>        &lt;input formControlName=&quot;confirmPassword&quot; type=&quot;password&quot; /&gt;<br>        &lt;span *ngIf=&quot;registerForm.errors?.[&#39;passwordMismatch&#39;] &amp;&amp;<br>                     registerForm.get(&#39;confirmPassword&#39;)?.touched&quot;&gt;<br>          Passwords do not match<br>        &lt;/span&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;button type=&quot;submit&quot; [disabled]=&quot;registerForm.invalid || isCheckingUsername&quot;&gt;<br>        Create Account<br>      &lt;/button&gt;</pre><pre>    &lt;/form&gt;<br>  `<br>})<br>export class RegisterComponent implements OnInit, OnDestroy {</pre><pre>  registerForm!: FormGroup;<br>  isCheckingUsername = false;<br>  usernameAvailable: boolean | null = null;<br>  passwordStrength = &#39;weak&#39;;<br>  passwordStrengthLabel = &#39;&#39;;</pre><pre>  private destroy$ = new Subject&lt;void&gt;();</pre><pre>  constructor(<br>    private fb: FormBuilder,<br>    private authService: AuthService<br>  ) {}</pre><pre>  ngOnInit(): void {<br>    this.registerForm = this.fb.group({<br>      username: [&#39;&#39;, [Validators.required, Validators.minLength(3)]],<br>      email: [&#39;&#39;, [Validators.required, Validators.email]],<br>      password: [&#39;&#39;, [Validators.required, Validators.minLength(8)]],<br>      confirmPassword: [&#39;&#39;, Validators.required]<br>    }, {<br>      validators: this.passwordMatchValidator<br>    });</pre><pre>    // --- RxJS Magic: Username availability check ---<br>    this.registerForm.get(&#39;username&#39;)!.valueChanges<br>      .pipe(<br>        debounceTime(500),                   // Wait 500ms after typing<br>        distinctUntilChanged(),              // Don&#39;t check if same value<br>        takeUntil(this.destroy$)<br>      )<br>      .subscribe(username =&gt; {<br>        if (username &amp;&amp; username.length &gt;= 3) {<br>          this.isCheckingUsername = true;<br>          this.usernameAvailable = null;</pre><pre>          this.authService.checkUsername(username)<br>            .pipe(takeUntil(this.destroy$))<br>            .subscribe({<br>              next: (isAvailable) =&gt; {<br>                this.usernameAvailable = isAvailable;<br>                this.isCheckingUsername = false;<br>              },<br>              error: () =&gt; {<br>                this.isCheckingUsername = false;<br>              }<br>            });<br>        } else {<br>          this.usernameAvailable = null;<br>        }<br>      });</pre><pre>    // --- RxJS Magic: Password strength meter ---<br>    this.registerForm.get(&#39;password&#39;)!.valueChanges<br>      .pipe(takeUntil(this.destroy$))<br>      .subscribe(password =&gt; {<br>        this.updatePasswordStrength(password || &#39;&#39;);<br>      });<br>  }</pre><pre>  private updatePasswordStrength(password: string): void {<br>    let score = 0;<br>    if (password.length &gt;= 8) score++;<br>    if (/[A-Z]/.test(password)) score++;<br>    if (/[0-9]/.test(password)) score++;<br>    if (/[^A-Za-z0-9]/.test(password)) score++;</pre><pre>    if (score &lt;= 1) {<br>      this.passwordStrength = &#39;weak&#39;;<br>      this.passwordStrengthLabel = &#39;🔴 Weak&#39;;<br>    } else if (score === 2) {<br>      this.passwordStrength = &#39;fair&#39;;<br>      this.passwordStrengthLabel = &#39;🟡 Fair&#39;;<br>    } else if (score === 3) {<br>      this.passwordStrength = &#39;good&#39;;<br>      this.passwordStrengthLabel = &#39;🟢 Good&#39;;<br>    } else {<br>      this.passwordStrength = &#39;strong&#39;;<br>      this.passwordStrengthLabel = &#39;💪 Strong&#39;;<br>    }<br>  }</pre><pre>  private passwordMatchValidator(group: AbstractControl) {<br>    const password = group.get(&#39;password&#39;)?.value;<br>    const confirm = group.get(&#39;confirmPassword&#39;)?.value;<br>    return password === confirm ? null : { passwordMismatch: true };<br>  }</pre><pre>  onSubmit(): void {<br>    if (this.registerForm.valid &amp;&amp; this.usernameAvailable) {<br>      console.log(&#39;Register:&#39;, this.registerForm.value);<br>    }<br>  }</pre><pre>  ngOnDestroy(): void {<br>    this.destroy$.next();<br>    this.destroy$.complete();<br>  }<br>}</pre><h3>🏙️ Real Example 2 — Dependent Dropdowns (Country → City)</h3><p>When selecting a country should dynamically load cities for that country:</p><pre>@Component({<br>  template: `<br>    &lt;form [formGroup]=&quot;addressForm&quot;&gt;</pre><pre>      &lt;select formControlName=&quot;country&quot;&gt;<br>        &lt;option value=&quot;&quot;&gt;Select Country&lt;/option&gt;<br>        &lt;option *ngFor=&quot;let c of countries&quot; [value]=&quot;c.code&quot;&gt;<br>          {{ c.name }}<br>        &lt;/option&gt;<br>      &lt;/select&gt;</pre><pre>      &lt;select formControlName=&quot;city&quot;&gt;<br>        &lt;option value=&quot;&quot;&gt;<br>          {{ isLoadingCities ? &#39;Loading cities...&#39; : &#39;Select City&#39; }}<br>        &lt;/option&gt;<br>        &lt;option *ngFor=&quot;let city of cities&quot; [value]=&quot;city.id&quot;&gt;<br>          {{ city.name }}<br>        &lt;/option&gt;<br>      &lt;/select&gt;</pre><pre>    &lt;/form&gt;<br>  `<br>})<br>export class AddressFormComponent implements OnInit, OnDestroy {</pre><pre>  addressForm = this.fb.group({<br>    country: [&#39;&#39;],<br>    city: [{ value: &#39;&#39;, disabled: true }]<br>  });</pre><pre>  countries = [<br>    { code: &#39;BD&#39;, name: &#39;Bangladesh&#39; },<br>    { code: &#39;IN&#39;, name: &#39;India&#39; },<br>    { code: &#39;US&#39;, name: &#39;USA&#39; }<br>  ];</pre><pre>  cities: any[] = [];<br>  isLoadingCities = false;</pre><pre>  private destroy$ = new Subject&lt;void&gt;();</pre><pre>  constructor(<br>    private fb: FormBuilder,<br>    private locationService: LocationService<br>  ) {}</pre><pre>  ngOnInit(): void {</pre><pre>    // When country changes — load its cities<br>    this.addressForm.get(&#39;country&#39;)!.valueChanges<br>      .pipe(<br>        takeUntil(this.destroy$),<br>        tap(() =&gt; {<br>          // Reset city when country changes<br>          this.cities = [];<br>          this.addressForm.get(&#39;city&#39;)!.disable();<br>          this.addressForm.get(&#39;city&#39;)!.setValue(&#39;&#39;);<br>          this.isLoadingCities = true;<br>        }),<br>        switchMap(countryCode =&gt; {<br>          if (!countryCode) return of([]);<br>          return this.locationService.getCitiesByCountry(countryCode)<br>            .pipe(catchError(() =&gt; of([])));<br>        })<br>      )<br>      .subscribe(cities =&gt; {<br>        this.cities = cities;<br>        this.isLoadingCities = false;<br>        if (cities.length &gt; 0) {<br>          this.addressForm.get(&#39;city&#39;)!.enable();<br>        }<br>      });<br>  }</pre><pre>  ngOnDestroy(): void {<br>    this.destroy$.next();<br>    this.destroy$.complete();<br>  }<br>}</pre><p>When the country changes, the city dropdown automatically:</p><ol><li>Resets to empty</li><li>Shows “Loading cities…”</li><li>Disables itself</li><li>Loads new cities from API</li><li>Re-enables with new options</li></ol><p>All powered by valueChanges + switchMap!</p><h3>💰 Real Example 3 — Live Price Calculator</h3><p>A checkout form where the price updates as you change quantity and select options:</p><pre>@Component({<br>  template: `<br>    &lt;form [formGroup]=&quot;orderForm&quot;&gt;<br>      &lt;label&gt;Quantity&lt;/label&gt;<br>      &lt;input type=&quot;number&quot; formControlName=&quot;quantity&quot; min=&quot;1&quot;&gt;</pre><pre>      &lt;label&gt;Size&lt;/label&gt;<br>      &lt;select formControlName=&quot;size&quot;&gt;<br>        &lt;option value=&quot;small&quot;&gt;Small&lt;/option&gt;<br>        &lt;option value=&quot;medium&quot;&gt;Medium (+৳200)&lt;/option&gt;<br>        &lt;option value=&quot;large&quot;&gt;Large (+৳400)&lt;/option&gt;<br>      &lt;/select&gt;</pre><pre>      &lt;label&gt;<br>        &lt;input type=&quot;checkbox&quot; formControlName=&quot;giftWrap&quot;&gt;<br>        Gift Wrap (+৳50)<br>      &lt;/label&gt;</pre><pre>      &lt;div class=&quot;price-summary&quot;&gt;<br>        &lt;p&gt;Base price: ৳{{ basePrice }}&lt;/p&gt;<br>        &lt;p&gt;Total: &lt;strong&gt;৳{{ liveTotal$ | async }}&lt;/strong&gt;&lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/form&gt;<br>  `<br>})<br>export class OrderFormComponent implements OnInit {</pre><pre>  basePrice = 500;</pre><pre>  orderForm = this.fb.group({<br>    quantity: [1],<br>    size: [&#39;small&#39;],<br>    giftWrap: [false]<br>  });</pre><pre>  liveTotal$!: Observable&lt;number&gt;;</pre><pre>  constructor(private fb: FormBuilder) {}</pre><pre>  ngOnInit(): void {<br>    const sizeAddon: Record&lt;string, number&gt; = {<br>      small: 0,<br>      medium: 200,<br>      large: 400<br>    };</pre><pre>    // Calculate total every time ANY field changes<br>    this.liveTotal$ = this.orderForm.valueChanges.pipe(<br>      startWith(this.orderForm.value),<br>      map(values =&gt; {<br>        const qty = values.quantity || 1;<br>        const sizeExtra = sizeAddon[values.size] || 0;<br>        const giftExtra = values.giftWrap ? 50 : 0;<br>        return (this.basePrice + sizeExtra + giftExtra) * qty;<br>      })<br>    );<br>  }<br>}</pre><p>The total updates <strong>instantly</strong> as the user changes any field — no button, no event handlers, just pure reactive magic!</p><h3>🔧 Using statusChanges for Async Validators</h3><pre>ngOnInit(): void {<br>  // React to form validity changes<br>  this.registerForm.statusChanges<br>    .pipe(<br>      distinctUntilChanged(),<br>      takeUntil(this.destroy$)<br>    )<br>    .subscribe(status =&gt; {<br>      // &#39;VALID&#39;, &#39;INVALID&#39;, &#39;PENDING&#39;, &#39;DISABLED&#39;<br>      if (status === &#39;VALID&#39;) {<br>        this.canSubmit = true;<br>        this.showSuccessHint = true;<br>      } else {<br>        this.canSubmit = false;<br>        this.showSuccessHint = false;<br>      }<br>    });<br>}</pre><h3>🧠 Chapter 8 Summary — What You Learned</h3><ul><li>FormControl.valueChanges is an Observable — you can use all RxJS operators on it</li><li>FormControl.statusChanges tells you when validity changes</li><li>Use debounceTime + switchMap for async validation (username check, email uniqueness)</li><li>Use valueChanges + switchMap for dependent dropdowns (country → city)</li><li>Use valueChanges + map + startWith for live price calculators and previews</li><li>Always clean up form subscriptions with takeUntil or async pipe</li></ul><h3>📚 Coming Up in Chapter 9…</h3><p>Chapter 9 covers <strong>debounceTime, </strong><strong>throttleTime, </strong><strong>distinctUntilChanged</strong> — the timing operators.</p><p>These are essential for search boxes, scroll events, resize events, and any situation where you need to control HOW OFTEN your code runs.</p><p>See you in Chapter 9! 🚀</p><p><em>💌 RxJS Deep Dive Newsletter Series | Chapter 8 of 10</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93707ce58fd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Actually Happens When You Type “What is Python?” Into ChatGPT]]></title>
            <link>https://medium.com/@jackpritomsoren/what-actually-happens-when-you-type-what-is-python-into-chatgpt-a55eaafe7ad3?source=rss-17ac2beef113------2</link>
            <guid isPermaLink="false">https://medium.com/p/a55eaafe7ad3</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Jack Pritom Soren]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 13:46:37 GMT</pubDate>
            <atom:updated>2026-06-25T14:12:47.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CLVsOO7jZHCF32YKIzJrQ.jpeg" /></figure><p>You type a question. A few seconds later, an answer streams back — fluent, confident, occasionally wrong. Most developers use this every single day without ever asking what’s actually happening between the keystroke and the response. And honestly, you don’t <em>need </em>to know. Until the day you do — the day your manager says “let’s add an AI feature to the product” and suddenly you’re the one who has to build it, not just use it.</p><p>That’s the moment most engineers hit a wall. Using ChatGPT is trivial. <em>Building on top of an LLM</em> is a different beast entirely — you’re suddenly dealing with API contracts, token limits, inconsistent outputs, five different providers with five different SDKs, and a model that occasionally decides your perfectly valid JSON request deserves a poem instead.</p><p>This article is the article I wish someone had handed me before I started. We’re going to go top to bottom: what an LLM actually is, what happens behind the scenes when you ask one a question, why every provider’s API feels like a slightly different flavor of the same headache, and how a framework called <strong>LangChain</strong> showed up to make that headache<br>manageable. By the end, you’ll understand not just the theory but the actual building</p><p>blocks — models, prompts, prompt templates, and structured output — that you’ll use to ship a real AI application.</p><p>No math. No model training. This is the practical, application-builder’s view of generative AI — the view from where you, the engineer integrating these models into products, actually stand.</p><h3>What We’ll Cover</h3><ol><li>The Three Layers of the Generative AI World</li><li>What an LLM Actually Is</li><li>What Happens When You Type “What is Python?”</li><li>The Provider Problem — Why Every API Feels Different</li><li>Enter LangChain: What It Actually Solves</li><li>LangChain’s Core Components</li><li>Prompts, Prompt Templates, and Structured Output</li><li>Common Pitfalls When You’re Starting Out</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBJuvfAJ0sr1q7K1_N6zhQ.png" /></figure><h3>Chapter 1: The Three Layers of the Generative AI World</h3><p>Before touching any code, it helps to mentally split the generative AI landscape into three layers. Almost every confusion beginners have comes from mixing these up.</p><p><strong>Layer 1 — Research.</strong> This is where new model architectures get invented. Think of the teams that publish papers on attention mechanisms, new training techniques, or ways to make models reason better. This is heavy math, heavy compute, and frankly — most application developers will never touch this layer, and that’s completely fine.</p><p><strong>Layer 2 — Foundation Models (the “bedrock”).</strong> This is where research turns into actual trained models — GPT-4, Claude, Gemini, Llama, and so on. These are massive neural networks trained on enormous amounts of text, trained once (at huge cost), and then exposed to the world either as downloadable weights or, more commonly, as a hosted service. You don’t train these. You consume them.</p><p><strong>Layer 3 — Providers.</strong> This is the business layer — companies that take a foundation model and wrap it in an API you can actually call. OpenAI serves GPT models through their API. Anthropic serves Claude. Google serves Gemini. Same underlying idea — “send text in, get text out” — but every provider wraps it differently.</p><p><strong>Layer 4 — You.</strong> This is where application engineers live. You don’t do research. You don’t train models. You take a provider’s API, combine it with your product’s logic, your data, your users’ inputs, and you build something useful on top — a chatbot, a document summarizer, an autonomous agent, whatever your product needs.</p><blockquote><em>💡 </em><strong><em>Pro tip:</em></strong><em> If you ever feel like you “need to learn machine learning” to build AI products, you usually don’t. You need to learn Layer 4 well — APIs, prompting, orchestration, and your product domain. ML research skills matter for Layers 1 and 2, which is a completely different career path.</em></blockquote><p>Here’s the mental model as a quick diagram:</p><pre>[ Research ]  →  [ Foundation Models ]  →  [ Providers ]  →  [ You: the App Builder ]<br>  (papers,         (GPT-4, Claude,           (OpenAI API,      (your product, your<br>   training         Gemini — trained          Anthropic API,    business logic, your<br>   techniques)       once, expensive)         Google API)       users)</pre><p>Everything in this article lives at Layer 4. That’s the layer where LangChain operates, and it’s the layer where most AI Engineering jobs actually sit.</p><h3>Chapter 2: What an LLM Actually Is</h3><p>Strip away the hype and an <strong>LLM (Large Language Model)</strong> is, at its core, a very sophisticated next-word predictor. That’s it. That’s the whole trick.</p><p>Here’s the analogy that actually makes this click: think about your phone’s keyboard autocomplete. You type “I’m running” and it suggests “late.” That’s a tiny, dumb version of what an LLM does. Now imagine that same autocomplete, except instead of being trained on a few thousand text messages, it was trained on a meaningful chunk of the publicly available internet — books, code, articles, forums, documentation. And instead of<br>predicting one word ahead with a simple lookup table, it predicts the next word (technically, the next <em>token</em> — a word piece) using a neural network with billions of parameters that has learned deep statistical patterns about how language, logic, and even code tend to flow.</p><p>That’s it. An LLM doesn’t “know” facts the way a database does. It doesn’t “look things up.” It generates the statistically most plausible continuation of the text you gave it, one token at a time, based on patterns absorbed during training.</p><p>This explains <em>so much</em> of LLM behavior that confuses beginners:</p><ul><li><strong>Why LLMs hallucinate:</strong> They’re not retrieving facts, they’re generating plausible text. If the plausible-sounding continuation happens to be false, the model has no internal alarm bell — it has no concept of “true” vs “false,” only “likely” vs “unlikely” given its training.</li><li><strong>Why phrasing your prompt differently changes the answer:</strong> You’re changing the starting point of the prediction, which changes what’s statistically “next.”</li><li><strong>Why longer context helps:</strong> More context = more signal for the model to condition its next-token predictions on.</li></ul><blockquote><em>⚠️ </em><strong><em>Heads up:</em></strong><em> Treating an LLM as a search engine or a database is the single most common beginner mistake. It’s a text-completion engine with extraordinary pattern recognition — powerful, but fundamentally different from a system that retrieves ground-truth facts. This is </em>exactly<em> why techniques like RAG (Retrieval-Augmented Generation) exist — to bolt real, retrievable facts onto a model that otherwise just predicts plausible text.</em></blockquote><h3>Chapter 3: What Happens When You Type “What is Python?”</h3><p>Let’s make this concrete. You open ChatGPT, type “What is Python?”, hit enter. Here’s the actual pipeline, simplified but accurate:</p><p><strong>Step 1 — Tokenization.</strong> Your text isn’t fed to the model as English words. It’s broken into <strong>tokens</strong> — sub-word chunks. “What is Python?” might become something like [&quot;What&quot;, &quot; is&quot;, &quot; Python&quot;, &quot;?&quot;], each mapped to a numeric ID the model actually understands. Models don&#39;t read letters; they read numbers.</p><p><strong>Step 2 — Embedding.</strong> Each token ID gets converted into a vector — a long list of numbers (think hundreds or thousands of dimensions) that represents that token’s meaning in a mathematical space. Tokens with similar meanings end up with mathematically similar vectors. This is how the model captures <em>meaning</em>, not just spelling.</p><p><strong>Step 3 — The Forward Pass (the actual “thinking”).</strong> These vectors flow through the model’s neural network layers — for modern LLMs, this is a <strong>transformer</strong> architecture, which uses a mechanism called <em>attention</em> to weigh how much every word in your input should influence every other word. This is the expensive, GPU-hungry computation step.</p><p><strong>Step 4 — Next-Token Prediction.</strong> The model outputs a probability distribution over its entire vocabulary — essentially “given everything so far, here’s how likely each possible next token is.” Maybe &quot;Python&quot; has a 40% chance of being followed by &quot; is&quot;, a 25% chance of &quot; was&quot;, and so on across thousands of candidate tokens.</p><p><strong>Step 5 — Sampling.</strong> The system picks one token from that distribution (not always the single most likely one — there’s controlled randomness, governed by a setting called <em>temperature</em>, which is why asking the same question twice can give slightly different answers).</p><p><strong>Step 6 — Repeat.</strong> That chosen token gets appended to the input, and the <em>entire process runs again</em> to predict the next token. This repeats — token by token — until the model produces a stop signal or hits a length limit.</p><p>That’s why responses <em>stream</em> in word by word — that’s not a UI trick, that’s literally how the generation works under the hood. Every word you see appear is a fresh pass through billions of parameters.</p><pre># A wildly simplified mental model of what&#39;s happening — NOT real model code,<br># just illustrating the loop structure of autoregressive generation.</pre><pre>prompt_tokens = tokenize(&quot;What is Python?&quot;)  # Step 1: text -&gt; tokens<br>generated = prompt_tokens</pre><pre>while not is_stop_token(generated[-1]) and len(generated) &lt; max_length:<br>    vectors = embed(generated)                 # Step 2: tokens -&gt; meaning vectors<br>    probabilities = model.forward(vectors)      # Steps 3-4: the transformer &quot;thinks&quot;<br>    next_token = sample(probabilities, temperature=0.7)  # Step 5: pick next token<br>    generated.append(next_token)                # Step 6: repeat with new context</pre><pre>response = detokenize(generated)</pre><p>Every single API call you make to OpenAI, Anthropic, or Google is, underneath all the infrastructure, running this loop.</p><h3>Chapter 4: The Provider Problem — Why Every API Feels Different</h3><p>Once you decide to build something real, you quickly discover that “calling an LLM” isn’t standardized. Here’s what that looks like in practice:</p><p>OpenAI’s chat completion format wraps messages in a messages array with role and content fields, and you call client.chat.completions.create(...). Anthropic&#39;s Claude<br>API looks similar on the surface but has different parameter names, a different way of handling system prompts, and different response object structures. Google&#39;s Gemini API differs again — different SDK, different conventions for multi-turn conversation, different ways of handling function calling.</p><p>Now multiply that by the actual problems teams run into:</p><ul><li><strong>Switching cost.</strong> You build your app on OpenAI, then your company wants to evaluate Claude for better reasoning on a specific task, or Gemini for cost reasons. Now you’re rewriting your integration layer from scratch.</li><li><strong>Inconsistent output formats.</strong> Getting reliable structured JSON out of one provider doesn’t mean the same prompting trick works on another. Each model has its own quirks.</li><li><strong>No standard for memory.</strong> If you want a chatbot that remembers earlier turns in a conversation, you have to manually manage and re-send conversation history — and every provider expects that history shaped slightly differently.</li><li><strong>No standard for tools/agents.</strong> Letting a model call external functions (e.g., “look up the weather,” “query a database”) is implemented differently across providers.</li><li><strong>Chaining is manual.</strong> Real applications rarely call an LLM once. You might retrieve documents, feed them into a prompt, get a response, parse it, feed <em>that</em> into another prompt. Wiring this by hand, per provider, gets messy fast.</li></ul><p>This is the exact pain point that gave rise to orchestration frameworks — and the most widely adopted one is <strong>LangChain</strong>.</p><h3>Chapter 5: Enter LangChain — What It Actually Solves</h3><p><strong>LangChain</strong> is a framework that sits between you and the raw LLM provider APIs, giving you a consistent set of abstractions regardless of which model is powering things underneath. Think of it less like “a new way to talk to AI” and more like an ORM (like SQLAlchemy or Prisma) — except instead of abstracting away different SQL databases, it abstracts away different LLM providers.</p><p>The pitch is simple: <strong>write your application logic once, swap the underlying model with minimal code changes.</strong> Switch from GPT-4 to Claude to test which gives better results? In a well-structured LangChain app, that can be close to a one-line change, not a rewrite.</p><p>But LangChain solves more than just “different APIs.” It gives you standardized, composable building blocks for the patterns that show up in <em>every</em> real LLM application: managing prompts as reusable templates, chaining multiple steps together, maintaining conversation memory, retrieving relevant data before generating a response, and letting<br>models call external tools as agents.</p><blockquote><em>⚠️ </em><strong><em>Heads up:</em></strong><em> LangChain is not magic and it’s not the only way to build AI<br>applications — you can absolutely call provider SDKs directly, and for simple use cases, that’s sometimes the better call (less abstraction overhead, fewer dependencies). Treat LangChain as a productivity tool for </em>composable, provider-agnostic<em> applications, not a mandatory layer for every project.</em></blockquote><h3>Chapter 6: LangChain’s Core Components</h3><p>LangChain is organized around a handful of core building blocks. If you understand these six, you understand the framework’s mental model.</p><p><strong>Models</strong> — The interface to the actual LLM. LangChain splits this into a few types:</p><ul><li><em>Chat/Language models</em> — text in, text out (or more precisely, message-in, message-out for chat models). This is your GPT-4, Claude, Gemini connections.</li><li><em>Embedding models</em> — instead of generating text, these convert text into those numeric vectors we discussed in Chapter 3, used for search and retrieval (this is the backbone of RAG systems).</li><li><em>Multimodal models</em> — models that accept more than just text: images, audio, sometimes video, alongside text.</li></ul><p><strong>Prompts</strong> — The input you construct to send to the model. We’ll go deep on this in the next chapter since it’s where most of your day-to-day engineering time actually goes.</p><p><strong>Chains</strong> — A sequence of calls linked together, where the output of one step becomes the input of the next. Classic example: take a user’s question → retrieve relevant documents → stuff those documents into a prompt → send to the LLM → parse the response. That’s a chain.</p><p><strong>Memory</strong> — A mechanism for persisting conversation history across multiple turns, so your chatbot doesn’t forget what the user said three messages ago. Without memory, every API call is stateless — the model has zero awareness of anything outside the current prompt.</p><p><strong>Indexes</strong> — Structures (usually backed by vector databases) that let you store and efficiently search large amounts of external data — your documents, your knowledge base — so the model can retrieve relevant pieces instead of trying to “know” everything.</p><p><strong>Agents</strong> — The most advanced building block. Instead of you hardcoding the sequence of steps, an agent uses the LLM itself to <em>decide</em> what action to take next — which tool to call, in what order — based on the user’s request. This is how you get an AI that can “search the web, then do math, then write a summary” without you scripting that exact flow.</p><pre>User question<br>     │<br>     ▼<br>[ Prompt Template ]  ← fills in variables (user input, retrieved context, etc.)<br>     │<br>     ▼<br>[ Chat Model ]  ← OpenAI, Claude, Gemini — swappable<br>     │<br>     ▼<br>[ Output Parser ]  ← turns raw text into structured data your app can use<br>     │<br>     ▼<br>Your application logic</pre><p>That diagram is, roughly, 80% of real-world LangChain usage. The remaining 20% layers in memory, retrieval, and agentic decision-making on top.</p><h3>Chapter 7: Prompts, Prompt Templates, and Structured Output</h3><p>This is the part that actually consumes most of your engineering time once you start building, so let’s slow down here.</p><h3>Simple Prompts vs. System + User Prompts</h3><p>The crudest way to prompt a model is a single block of text — you just write what you want and send it. That works for quick experiments but falls apart fast in production.</p><p>Modern chat models instead expect a <strong>structured message format</strong>, typically split into<br>roles:</p><ul><li><strong>System prompt</strong> — instructions that set the model’s behavior, persona, and constraints <em>before</em> the conversation starts. Think of it as the model’s “job description.” (“You are a customer support assistant for a SaaS billing platform. Only answer questions related to billing. Keep responses under 100 words.”)</li><li><strong>User prompt</strong> — the actual input from the end user. (“Why was I charged twice this month?”)</li></ul><p>Separating these matters enormously. Mixing instructions and user input into one giant blob makes the model more likely to follow user instructions that override your intended behavior (a real security concern — this is part of how prompt injection attacks work). Keeping them separate is both cleaner <em>and</em> safer.</p><pre># Simple prompt — works, but rigid and hard to reuse or secure<br>simple_prompt = &quot;You are a billing assistant. Why was I charged twice?&quot;</pre><pre># System + User separation — the standard production pattern<br>messages = [<br>    {<br>        &quot;role&quot;: &quot;system&quot;,<br>        &quot;content&quot;: &quot;You are a customer support assistant for a SaaS billing platform. &quot;<br>                    &quot;Only answer questions related to billing. Keep responses concise.&quot;<br>    },<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Why was I charged twice this month?&quot;<br>    }<br>]</pre><h3>Prompt Templates</h3><p>Here’s a problem you’ll hit on day one of building anything real: your system prompt is mostly static, but parts of it need to change based on context — the user’s name, the retrieved documents, the current date, the product they’re asking about. Hardcoding f-strings everywhere gets messy and error-prone fast, especially once you have dozens of prompts across your codebase.</p><p><strong>Prompt templates</strong> solve this by treating prompts like reusable functions with parameters — define the structure once, fill in the variables at call time.</p><pre>from langchain.prompts import ChatPromptTemplate</pre><pre># Define the template ONCE, with placeholders for dynamic values<br>template = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;You are a support assistant for {product_name}. &quot;<br>               &quot;Today&#39;s date is {current_date}. Be concise and friendly.&quot;),<br>    (&quot;user&quot;, &quot;{user_question}&quot;)<br>])</pre><pre># Reuse it for every request — just swap in the variables<br>filled_prompt = template.format_messages(<br>    product_name=&quot;Acme Billing&quot;,<br>    current_date=&quot;2026-06-21&quot;,<br>    user_question=&quot;Why was I charged twice this month?&quot;<br>)</pre><p>This isn’t just convenience. Templates make prompts <strong>testable</strong> (you can version them, diff them, A/B test wording changes), <strong>consistent</strong> (every call follows the same structure, reducing weird edge-case outputs), and <strong>maintainable</strong> (update the template in one place instead of hunting through scattered strings across your codebase).</p><blockquote><em>💡 </em><strong><em>Pro tip:</em></strong><em> Treat your prompt templates the way you’d treat SQL queries or API contracts — version-controlled, reviewed in pull requests, and tested. A “small” wording tweak in a system prompt can meaningfully change model behavior in production.</em></blockquote><h3>Structured Output</h3><p>Here’s the next wall every builder hits: LLMs naturally produce free-flowing text, but your application needs <em>data</em> — a JSON object you can parse, validate, and plug into a database or UI. “Just ask the model to return JSON” sounds simple and, often, isn’t — models sometimes wrap JSON in explanatory prose, use inconsistent field names, or produce almost-valid-but-broken JSON.</p><p>LangChain addresses this with <strong>structured output</strong> tooling — you define the <em>shape</em> of data you want (often using a schema, like a Pydantic model in Python), and LangChain handles instructing the model to conform to it and parsing/validating the result.</p><pre>from pydantic import BaseModel, Field<br>from langchain.chat_models import init_chat_model</pre><pre># Define the EXACT shape of data you want back — not free text<br>class SupportTicketSummary(BaseModel):<br>    issue_category: str = Field(description=&quot;One of: billing, technical, account, other&quot;)<br>    urgency: str = Field(description=&quot;One of: low, medium, high&quot;)<br>    summary: str = Field(description=&quot;One sentence summary of the user&#39;s issue&quot;)</pre><pre>model = init_chat_model(&quot;gpt-4&quot;, model_provider=&quot;openai&quot;)</pre><pre># Bind the schema — the model&#39;s response will be coerced into this structure<br>structured_model = model.with_structured_output(SupportTicketSummary)</pre><pre>result = structured_model.invoke(<br>    &quot;Why was I charged twice this month? This is really frustrating, &quot;<br>    &quot;I need this fixed before my card gets declined again.&quot;<br>)</pre><pre># &#39;result&#39; is now a validated SupportTicketSummary object, not raw text:<br># SupportTicketSummary(<br>#     issue_category=&quot;billing&quot;,<br>#     urgency=&quot;high&quot;,<br>#     summary=&quot;User was double-charged and needs urgent resolution.&quot;<br># )</pre><p>This is the difference between “an AI feature that’s a fun demo” and “an AI feature that reliably feeds your database without crashing on a malformed response.” Structured output is, in practice, one of the highest-leverage things to get right early — almost every real AI feature eventually needs the model’s output to plug into <em>something</em> downstream: a UI component, a database row, an API call to another system.</p><h3>Chapter 8: Common Pitfalls When You’re Starting Out</h3><p>A few things that trip up almost everyone in their first few weeks of AI application<br>development:</p><ul><li><strong>Treating the system prompt as a suggestion, not a contract.</strong> Vague system prompts (“be helpful”) produce inconsistent behavior. Specific, constrained system prompts produce reliable behavior. Be explicit about scope, tone, format, and what the model should refuse to do.</li><li><strong>Skipping output validation.</strong> Even with structured output tooling, always validate what comes back before trusting it downstream — models can still fail to conform perfectly, especially with complex nested schemas.</li><li><strong>Forgetting that “memory” isn’t automatic.</strong> Without explicit memory handling, every API call is a blank slate. If your chatbot seems to have amnesia, it’s because you’re not re-sending prior conversation turns.</li><li><strong>Over-engineering with agents too early.</strong> Agents are powerful but unpredictable and harder to debug than a fixed chain. Start with a simple, deterministic chain. Reach for agents only when the task genuinely requires dynamic decision-making.</li><li><strong>Ignoring token costs and limits.</strong> Every provider charges per token and enforces context length limits. Long conversation histories, large retrieved documents, and verbose system prompts all add up fast — both in cost and in risk of hitting context limits.</li></ul><h3>Wrapping Up</h3><p>If there’s one mental model to walk away with, it’s this: an LLM is a next-token predictor wrapped behind a provider’s API, and everything you build sits on top of that simple loop. The real engineering work — the part that actually makes a product good — isn’t in the model itself. It’s in how well you structure your prompts, how reliably you turn model output into usable data, and how thoughtfully you chain steps together to solve an actual<br>user problem.</p><p>LangChain doesn’t replace that thinking — it gives you a consistent vocabulary and toolkit to express it, regardless of which provider’s model happens to sit underneath. Learn the six building blocks — models, prompts, chains, memory, indexes, agents — and you’ll find that almost every AI application you encounter, no matter how complex it looks from the outside, is built from some combination of these same simple pieces.</p><p>The next step from here is hands-on: pick a tiny project — a document Q&amp;A bot, a structured data extractor from messy text, anything real — and build it with a prompt template and structured output from the start. That’s where this stuff actually clicks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a55eaafe7ad3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS in Angular — Chapter 7 | Combining Observables — `forkJoin`, `combineLatest`, `zip` & More]]></title>
            <link>https://medium.com/@jackpritomsoren/rxjs-in-angular-chapter-7-combining-observables-forkjoin-combinelatest-zip-more-529199ed8949?source=rss-17ac2beef113------2</link>
            <guid isPermaLink="false">https://medium.com/p/529199ed8949</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jack Pritom Soren]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 13:36:08 GMT</pubDate>
            <atom:updated>2026-06-21T13:36:08.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GfCo-X9dUHqyISePNjEjWQ.jpeg" /></figure><h3>“Combining Observables — forkJoin, combineLatest, zip &amp; More&quot;</h3><h3>👋 Welcome to Chapter 7!</h3><p>Real apps rarely get data from just <strong>one place</strong>. A product page might need:</p><ul><li>The product details (from /api/products/5)</li><li>The user’s wishlist (from /api/wishlist)</li><li>The store’s discount config (from /api/config)</li></ul><p>How do you handle <strong>multiple Observables</strong> at the same time?</p><p>That’s what today’s combination operators are for!</p><h3>🍽️ The Restaurant Kitchen Analogy</h3><p>Imagine a chef 👨‍🍳 preparing a 3-course meal:</p><p><strong>forkJoin</strong> — &quot;Start cooking all 3 dishes at the same time. Serve the full meal ONLY when ALL dishes are ready.&quot;<br>→ Wait for ALL to complete, then give you all results together</p><p><strong>combineLatest</strong> — &quot;Whenever ANY dish is updated, bring out the current status of all dishes.&quot;<br>→ Every time any Observable emits, give you the latest value from all</p><p><strong>zip</strong> — &quot;Match dish from kitchen 1 with dish from kitchen 2, one pair at a time.&quot;<br>→ Pairs values by position</p><p>Let’s see each one in detail.</p><h3>🍴 forkJoin — Wait for All, Then Done</h3><p>forkJoin runs multiple Observables <strong>in parallel</strong> and waits until <strong>all of them complete</strong>. Then it emits all the results at once.</p><p>Like Promise.all() but for Observables!</p><h3>Simple Example</h3><pre>import { forkJoin, of } from &#39;rxjs&#39;;<br>import { delay } from &#39;rxjs/operators&#39;;</pre><pre>forkJoin({<br>  users: of([&#39;Alice&#39;, &#39;Bob&#39;]).pipe(delay(1000)),<br>  products: of([&#39;Apple&#39;, &#39;Banana&#39;]).pipe(delay(500)),<br>  config: of({ theme: &#39;dark&#39; }).pipe(delay(200))<br>}).subscribe(results =&gt; {<br>  console.log(results.users);    // [&#39;Alice&#39;, &#39;Bob&#39;]<br>  console.log(results.products); // [&#39;Apple&#39;, &#39;Banana&#39;]<br>  console.log(results.config);   // { theme: &#39;dark&#39; }<br>});<br>// All three run in PARALLEL. Total wait time = 1000ms (the slowest)<br>// If it were sequential, total = 1700ms</pre><h3>Real Angular Example — Loading a Dashboard</h3><pre>// dashboard.component.ts<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { forkJoin } from &#39;rxjs&#39;;</pre><pre>@Component({<br>  selector: &#39;app-dashboard&#39;,<br>  template: `<br>    &lt;div *ngIf=&quot;!isLoading&quot;&gt;<br>      &lt;div class=&quot;stats-card&quot;&gt;<br>        &lt;h3&gt;Total Users&lt;/h3&gt;<br>        &lt;p&gt;{{ stats?.totalUsers }}&lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;stats-card&quot;&gt;<br>        &lt;h3&gt;Orders Today&lt;/h3&gt;<br>        &lt;p&gt;{{ stats?.ordersToday }}&lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;stats-card&quot;&gt;<br>        &lt;h3&gt;Revenue&lt;/h3&gt;<br>        &lt;p&gt;৳{{ stats?.revenue }}&lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;recent-orders&quot;&gt;<br>        &lt;h3&gt;Recent Orders&lt;/h3&gt;<br>        &lt;div *ngFor=&quot;let order of recentOrders&quot;&gt;<br>          {{ order.id }} — {{ order.status }}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;</pre><pre>    &lt;div *ngIf=&quot;isLoading&quot;&gt;Loading dashboard... ⏳&lt;/div&gt;<br>    &lt;div *ngIf=&quot;error&quot;&gt;{{ error }}&lt;/div&gt;<br>  `<br>})<br>export class DashboardComponent implements OnInit {</pre><pre>  stats: any = null;<br>  recentOrders: any[] = [];<br>  isLoading = true;<br>  error = &#39;&#39;;</pre><pre>  constructor(<br>    private statsService: StatsService,<br>    private orderService: OrderService<br>  ) {}</pre><pre>  ngOnInit(): void {<br>    // Load BOTH at the same time — wait for both to finish<br>    forkJoin({<br>      stats: this.statsService.getDashboardStats(),<br>      orders: this.orderService.getRecentOrders(5)<br>    }).subscribe({<br>      next: ({ stats, orders }) =&gt; {<br>        this.stats = stats;<br>        this.recentOrders = orders;<br>        this.isLoading = false;<br>      },<br>      error: (err) =&gt; {<br>        this.error = &#39;Failed to load dashboard data&#39;;<br>        this.isLoading = false;<br>      }<br>    });<br>  }<br>}</pre><p>⚠️ <strong>Important: </strong><strong>forkJoin only works with Observables that COMPLETE!</strong></p><p>HttpClient calls complete after one response ✅<br>BehaviorSubject never completes ❌ (use combineLatest instead)</p><h3>🔄 combineLatest — React to Any Change</h3><p>combineLatest watches multiple Observables and <strong>every time any one of them emits</strong>, it gives you the <strong>latest values from ALL of them</strong>.</p><p>It’s perfect for filter/search UIs where changing any filter should update the results.</p><h3>Simple Example</h3><pre>import { combineLatest, BehaviorSubject } from &#39;rxjs&#39;;</pre><pre>const searchTerm$ = new BehaviorSubject&lt;string&gt;(&#39;&#39;);<br>const category$ = new BehaviorSubject&lt;string&gt;(&#39;all&#39;);<br>const priceMax$ = new BehaviorSubject&lt;number&gt;(1000);</pre><pre>combineLatest([searchTerm$, category$, priceMax$])<br>  .subscribe(([search, category, maxPrice]) =&gt; {<br>    console.log(`Search: ${search}, Category: ${category}, Max: ${maxPrice}`);<br>  });</pre><pre>// Output immediately: Search: , Category: all, Max: 1000</pre><pre>searchTerm$.next(&#39;phone&#39;);<br>// Output: Search: phone, Category: all, Max: 1000</pre><pre>category$.next(&#39;electronics&#39;);<br>// Output: Search: phone, Category: electronics, Max: 1000</pre><pre>priceMax$.next(500);<br>// Output: Search: phone, Category: electronics, Max: 500</pre><p>Every time <strong>any</strong> filter changes, you get all three latest values!</p><h3>Real Angular Example — Product Filter Page</h3><pre>// product-filter.component.ts<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormControl } from &#39;@angular/forms&#39;;<br>import { combineLatest, Observable } from &#39;rxjs&#39;;<br>import { map, startWith, debounceTime } from &#39;rxjs/operators&#39;;</pre><pre>@Component({<br>  selector: &#39;app-product-filter&#39;,<br>  template: `<br>    &lt;div class=&quot;filters&quot;&gt;<br>      &lt;input [formControl]=&quot;searchControl&quot; placeholder=&quot;Search...&quot;&gt;</pre><pre>      &lt;select [formControl]=&quot;categoryControl&quot;&gt;<br>        &lt;option value=&quot;all&quot;&gt;All Categories&lt;/option&gt;<br>        &lt;option value=&quot;electronics&quot;&gt;Electronics&lt;/option&gt;<br>        &lt;option value=&quot;clothing&quot;&gt;Clothing&lt;/option&gt;<br>        &lt;option value=&quot;food&quot;&gt;Food&lt;/option&gt;<br>      &lt;/select&gt;</pre><pre>      &lt;label&gt;Max Price: ৳{{ priceControl.value }}&lt;/label&gt;<br>      &lt;input type=&quot;range&quot; [formControl]=&quot;priceControl&quot; min=&quot;0&quot; max=&quot;10000&quot; step=&quot;100&quot;&gt;<br>    &lt;/div&gt;</pre><pre>    &lt;p&gt;Showing {{ (filteredProducts$ | async)?.length }} products&lt;/p&gt;</pre><pre>    &lt;div *ngFor=&quot;let product of filteredProducts$ | async&quot; class=&quot;product-card&quot;&gt;<br>      &lt;h3&gt;{{ product.name }}&lt;/h3&gt;<br>      &lt;span&gt;৳{{ product.price }}&lt;/span&gt;<br>      &lt;span class=&quot;tag&quot;&gt;{{ product.category }}&lt;/span&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class ProductFilterComponent implements OnInit {</pre><pre>  searchControl = new FormControl(&#39;&#39;);<br>  categoryControl = new FormControl(&#39;all&#39;);<br>  priceControl = new FormControl(10000);</pre><pre>  allProducts: Product[] = [];<br>  filteredProducts$!: Observable&lt;Product[]&gt;;</pre><pre>  constructor(private productService: ProductService) {}</pre><pre>  ngOnInit(): void {<br>    // First, load all products<br>    this.productService.getProducts().subscribe(products =&gt; {<br>      this.allProducts = products;<br>    });</pre><pre>    // Watch all three filters — update results whenever any changes<br>    this.filteredProducts$ = combineLatest([<br>      this.searchControl.valueChanges.pipe(startWith(&#39;&#39;), debounceTime(300)),<br>      this.categoryControl.valueChanges.pipe(startWith(&#39;all&#39;)),<br>      this.priceControl.valueChanges.pipe(startWith(10000))<br>    ]).pipe(<br>      map(([search, category, maxPrice]) =&gt; {<br>        return this.allProducts.filter(product =&gt; {</pre><pre>          const matchesSearch = !search ||<br>            product.name.toLowerCase().includes(search.toLowerCase());</pre><pre>          const matchesCategory = category === &#39;all&#39; ||<br>            product.category === category;</pre><pre>          const matchesPrice = product.price &lt;= (maxPrice || 10000);</pre><pre>          return matchesSearch &amp;&amp; matchesCategory &amp;&amp; matchesPrice;<br>        });<br>      })<br>    );<br>  }<br>}</pre><p>This is real production-grade code! The filter UI updates instantly as the user adjusts any control — no button needed!</p><h3>🤝 withLatestFrom — Use the Latest Value Without Triggering</h3><p>withLatestFrom is like combineLatest, but it only triggers when the <strong>first Observable</strong> emits — it just grabs the latest value from the others as a &quot;snapshot&quot;.</p><pre>import { withLatestFrom } from &#39;rxjs/operators&#39;;</pre><pre>// When a button is clicked, grab the current user and filter state<br>buttonClick$<br>  .pipe(<br>    withLatestFrom(currentUser$, activeFilters$)<br>  )<br>  .subscribe(([clickEvent, user, filters]) =&gt; {<br>    // Only triggered by clicks, but we have user and filters available<br>    this.logUserAction(user, filters, &#39;EXPORT&#39;);<br>  });</pre><h3>Real Example — Save Button with Form State</h3><pre>// When save is clicked, capture the CURRENT form values<br>this.saveButton.clicks$<br>  .pipe(<br>    withLatestFrom(this.form.valueChanges.pipe(startWith(this.form.value)))<br>  )<br>  .subscribe(([_, formValues]) =&gt; {<br>    this.save(formValues);<br>  });</pre><h3>🤐 zip — Pair by Position</h3><p>zip waits for ALL Observables to emit one value, then combines them by position. Like a zipper — left tooth, right tooth, left tooth, right tooth...</p><pre>import { zip, of } from &#39;rxjs&#39;;</pre><pre>const names$ = of(&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;);<br>const scores$ = of(95, 87, 92);<br>const grades$ = of(&#39;A&#39;, &#39;B+&#39;, &#39;A-&#39;);</pre><pre>zip(names$, scores$, grades$).subscribe(([name, score, grade]) =&gt; {<br>  console.log(`${name}: ${score} (${grade})`);<br>});</pre><pre>// Output:<br>// Alice: 95 (A)<br>// Bob: 87 (B+)<br>// Charlie: 92 (A-)</pre><p>zip is less commonly used in Angular, but handy when you need to pair corresponding items.</p><h3>🏗️ Full Real-World Example — Product Detail Page</h3><p>A product detail page often needs data from multiple APIs. Here’s the complete pattern:</p><pre>// product-detail.component.ts<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { ActivatedRoute } from &#39;@angular/router&#39;;<br>import { forkJoin, combineLatest, Observable, EMPTY } from &#39;rxjs&#39;;<br>import { switchMap, catchError, map } from &#39;rxjs/operators&#39;;</pre><pre>interface PageData {<br>  product: Product;<br>  reviews: Review[];<br>  isInWishlist: boolean;<br>  relatedProducts: Product[];<br>}</pre><pre>@Component({<br>  selector: &#39;app-product-detail&#39;,<br>  template: `<br>    &lt;ng-container *ngIf=&quot;pageData$ | async as data&quot;&gt;<br>      &lt;div class=&quot;product-hero&quot;&gt;<br>        &lt;h1&gt;{{ data.product.name }}&lt;/h1&gt;<br>        &lt;p&gt;{{ data.product.description }}&lt;/p&gt;<br>        &lt;p class=&quot;price&quot;&gt;৳{{ data.product.price }}&lt;/p&gt;</pre><pre>        &lt;button [class.active]=&quot;data.isInWishlist&quot; (click)=&quot;toggleWishlist()&quot;&gt;<br>          {{ data.isInWishlist ? &#39;❤️ Wishlisted&#39; : &#39;🤍 Add to Wishlist&#39; }}<br>        &lt;/button&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;section class=&quot;reviews&quot;&gt;<br>        &lt;h2&gt;Reviews ({{ data.reviews.length }})&lt;/h2&gt;<br>        &lt;div *ngFor=&quot;let review of data.reviews&quot;&gt;<br>          &lt;strong&gt;{{ review.author }}&lt;/strong&gt;<br>          &lt;span&gt;⭐ {{ review.rating }}&lt;/span&gt;<br>          &lt;p&gt;{{ review.comment }}&lt;/p&gt;<br>        &lt;/div&gt;<br>      &lt;/section&gt;</pre><pre>      &lt;section class=&quot;related&quot;&gt;<br>        &lt;h2&gt;Related Products&lt;/h2&gt;<br>        &lt;div *ngFor=&quot;let related of data.relatedProducts&quot; class=&quot;mini-card&quot;&gt;<br>          {{ related.name }} — ৳{{ related.price }}<br>        &lt;/div&gt;<br>      &lt;/section&gt;<br>    &lt;/ng-container&gt;</pre><pre>    &lt;div *ngIf=&quot;isLoading&quot;&gt;Loading... ⏳&lt;/div&gt;<br>    &lt;div *ngIf=&quot;errorMessage&quot;&gt;{{ errorMessage }}&lt;/div&gt;<br>  `<br>})<br>export class ProductDetailComponent implements OnInit {</pre><pre>  pageData$!: Observable&lt;PageData&gt;;<br>  isLoading = true;<br>  errorMessage = &#39;&#39;;</pre><pre>  constructor(<br>    private route: ActivatedRoute,<br>    private productService: ProductService,<br>    private reviewService: ReviewService,<br>    private wishlistService: WishlistService<br>  ) {}</pre><pre>  ngOnInit(): void {</pre><pre>    this.pageData$ = this.route.params.pipe(<br>      switchMap(params =&gt; {<br>        const id = params[&#39;id&#39;];</pre><pre>        // Load ALL data for this product in parallel<br>        return forkJoin({<br>          product: this.productService.getProduct(id),<br>          reviews: this.reviewService.getReviews(id),<br>          isInWishlist: this.wishlistService.isInWishlist(id),<br>          relatedProducts: this.productService.getRelated(id)<br>        });<br>      }),<br>      catchError(err =&gt; {<br>        this.errorMessage = &#39;Failed to load product details&#39;;<br>        this.isLoading = false;<br>        return EMPTY;<br>      })<br>    );</pre><pre>    // Track loading state<br>    this.pageData$.subscribe(() =&gt; {<br>      this.isLoading = false;<br>    });<br>  }</pre><pre>  toggleWishlist(): void {<br>    // ... toggle logic<br>  }<br>}</pre><p>Everything loads in parallel, the route handles navigation, and errors are caught gracefully — all in one clean stream!</p><h3>🧠 Choosing the Right Combination Operator</h3><p><strong>forkJoin</strong> — &quot;Load everything once, wait for all to finish, give me all results&quot;<br>Best for: page initialization, loading multiple API resources at once</p><p><strong>combineLatest</strong> — &quot;Every time ANYTHING changes, give me all the latest values&quot;<br>Best for: filter/search UIs, forms with live preview, dashboards with real-time updates</p><p><strong>withLatestFrom</strong> — &quot;When THIS happens, also give me the latest value of THAT&quot;<br>Best for: button clicks that need current state, actions that depend on form values</p><p><strong>zip</strong> — &quot;Match item 1 with item 1, item 2 with item 2...&quot;<br>Best for: combining two arrays where order corresponds</p><h3>🧠 Chapter 7 Summary — What You Learned</h3><ul><li><strong>forkJoin</strong> runs multiple Observables in parallel and emits all results when ALL complete — like Promise.all()</li><li><strong>combineLatest</strong> emits whenever any Observable emits, always giving you the latest from all — perfect for filter UIs</li><li><strong>withLatestFrom</strong> only triggers from one source, but snapshots the latest value from others</li><li><strong>zip</strong> pairs values by position from multiple Observables</li><li>These operators are essential for building real-world pages that need data from multiple sources</li></ul><h3>📚 Coming Up in Chapter 8…</h3><p>One of the most powerful and real-world RxJS patterns in Angular:</p><p><strong>Angular Forms + RxJS</strong> — how to build reactive forms with live validation, dependent fields, and dynamic behavior using valueChanges, statusChanges, and the operators we&#39;ve learned!</p><p>See you in Chapter 8! 🚀</p><p><em>💌 RxJS Deep Dive Newsletter Series | Chapter 7 of 10</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=529199ed8949" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The JavaScript Event Loop: Why Your Code Doesn’t Do What You Think It Does]]></title>
            <link>https://medium.com/@jackpritomsoren/the-javascript-event-loop-why-your-code-doesnt-do-what-you-think-it-does-a4982f45545d?source=rss-17ac2beef113------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4982f45545d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[event-loop]]></category>
            <dc:creator><![CDATA[Jack Pritom Soren]]></dc:creator>
            <pubDate>Fri, 15 May 2026 13:07:48 GMT</pubDate>
            <atom:updated>2026-05-15T13:07:48.443Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_31G8wnaK8ukGXKKmZ7suQ.jpeg" /></figure><p>JavaScript is single-threaded. One thread. One call stack. One thing at a time.</p><p>And yet — you’ve written code that fetches data from an API <em>while</em> animating a loading spinner <em>while</em> handling button clicks <em>while</em> running a countdown timer. How? How does one thread do all of that without freezing?</p><p>The answer is the <strong>event loop</strong> — arguably the most misunderstood piece of the JavaScript runtime. Most developers use it every day without ever truly seeing it. They write setTimeout, Promise.then(), async/await, and fetch() like they&#39;re magic spells, and they mostly work — until they don&#39;t.</p><p>Until you’ve hit a bug where a setTimeout(..., 0) fires <em>after</em> something it should have fired <em>before</em>. Until a Promise resolves in an order that makes no logical sense to you. Until your UI freezes solid because a loop ran too long. That&#39;s when you realize: you&#39;ve been flying blind.</p><p>Understanding the event loop isn’t just academic. It’s the difference between writing JavaScript that <em>works</em> and writing JavaScript that you <em>understand</em>. It explains why async/await is not the same as threads, why microtasks beat macrotasks, and why your beautiful Promise chain sometimes feels like it has a mind of its own.</p><p>This article is the deep dive nobody wrote clearly enough. By the end, you’ll be able to look at any piece of async JavaScript and trace — in your head, step by step — exactly what order things will execute and why.</p><h3>What We’ll Cover</h3><ol><li>The Single-Threaded Reality</li><li>The Call Stack — JavaScript’s Working Memory</li><li>The Web APIs Layer — Where Async Work Actually Happens</li><li>The Callback Queue (Macrotask Queue)</li><li>The Microtask Queue — The Queue That Jumps the Line</li><li>The Event Loop — The Conductor Tying It All Together</li><li>setTimeout and setInterval — What They Actually Promise</li><li>Promises and the Microtask Queue</li><li>async/await — Syntactic Sugar with Real Consequences</li><li>Real-World Execution Order Puzzles (With Solutions)</li><li>Pitfalls That Will Bite You in Production</li><li>Conclusion — The Mental Model You’ll Keep Forever</li></ol><h3>1. The Single-Threaded Reality</h3><p>Let’s start with what “single-threaded” actually means, because it’s more nuanced than it sounds.</p><p>A <strong>thread</strong> is a sequence of instructions a CPU can execute. Some languages — Java, Go, C++ — are multi-threaded, meaning they can genuinely run multiple instruction sequences <em>simultaneously</em> on different CPU cores. They share memory, they can race each other, and you need mutexes and semaphores and all sorts of painful synchronization primitives to keep them from stepping on each other.</p><p>JavaScript deliberately chose <em>not</em> to do that. One thread. No shared memory races. No deadlocks. No mutexes.</p><p>But here’s the thing people miss: <strong>JavaScript is single-threaded, but the browser (or Node.js) is not.</strong> The runtime environment — Chrome, Firefox, Node — is heavily multi-threaded. It has threads for network I/O, file I/O, timers, rendering, garbage collection, and more. JavaScript itself runs on one thread, but it <em>delegates</em> slow work to those other threads.</p><p>The event loop is the mechanism by which results from those other threads get handed back to your JavaScript code, safely, one at a time.</p><h3>2. The Call Stack — JavaScript’s Working Memory</h3><p>The <strong>call stack</strong> is where JavaScript tracks what it’s currently executing. It’s a stack data structure — last in, first out — and every time you call a function, a new <strong>stack frame</strong> gets pushed on top. When the function returns, that frame gets popped off.</p><pre>function greet(name) {<br>    return `Hello, ${name}!`;         // 3. This executes, returns<br>}</pre><pre>function main() {<br>    const message = greet(&quot;Fatima&quot;);  // 2. greet() is pushed onto stack<br>    console.log(message);             // 4. console.log is pushed, executes, pops<br>}</pre><pre>main();                               // 1. main() is pushed onto stack</pre><p>Execution trace:</p><pre>[] → [main] → [main, greet] → [main] → [main, console.log] → [main] → []</pre><p>The call stack is synchronous and blocking. If you put a while(true) loop in there, the stack never clears. Nothing else runs. Your UI freezes. The browser tab hangs.</p><p>This is why long-running synchronous operations are the enemy. They hold the stack hostage.</p><h3>3. The Web APIs Layer — Where Async Work Actually Happens</h3><p>When you call fetch(), setTimeout(), addEventListener(), or fs.readFile() — you are <em>not</em> running JavaScript. You&#39;re calling into the <strong>Web APIs</strong> layer (in the browser) or the <strong>Node.js C++ APIs</strong> layer.</p><p>Think of it like handing off a task to a dedicated department:</p><ul><li>“Go make this HTTP request. Come back when you have a response.”</li><li>“Set a timer for 500ms. Come back when it fires.”</li><li>“Watch this DOM element for a click. Come back when it happens.”</li></ul><p>JavaScript doesn’t wait. It just hands off the task, registers a callback, and moves on. The API does the work — off the main thread, in the background — and when it’s done, it puts your callback in a queue.</p><pre>console.log(&quot;1 — Starting&quot;);</pre><pre>// This call goes to the Timer Web API.<br>// JavaScript does NOT wait here. It just registers the callback and moves on.<br>setTimeout(() =&gt; {<br>    console.log(&quot;3 — Timer fired&quot;);<br>}, 1000);</pre><pre>console.log(&quot;2 — Already past the setTimeout&quot;);</pre><pre>// Output:<br>// 1 — Starting<br>// 2 — Already past the setTimeout<br>// (1 second later...)<br>// 3 — Timer fired</pre><p>JavaScript handed the timer to the browser, said “call me back in 1000ms,” and kept running. That’s non-blocking I/O in a nutshell.</p><h3>4. The Callback Queue (Macrotask Queue)</h3><p>When an async operation completes — a timer fires, a network response arrives, a click event triggers — the callback associated with it gets placed in the <strong>callback queue</strong> (also called the <strong>macrotask queue</strong> or <strong>task queue</strong>).</p><p>This queue holds tasks waiting for their turn to run. They can’t jump onto the call stack directly. They have to wait.</p><p>Common sources of macrotasks:</p><ul><li>setTimeout callbacks</li><li>setInterval callbacks</li><li>I/O callbacks (file reads, network responses in Node.js)</li><li>UI event handlers (click, keydown, scroll)</li><li>postMessage callbacks</li><li>setImmediate (Node.js only)</li></ul><p>The queue is processed one task at a time. Each task runs to completion — no interruption. If a task takes 500ms, the browser is locked for 500ms. This is why you’ll sometimes see the browser devtools warn about “long tasks.”</p><h3>5. The Microtask Queue — The Queue That Jumps the Line</h3><p>Here’s where most developers’ mental models break down.</p><p>There are <em>two</em> queues, not one. The second is the <strong>microtask queue</strong>, and it has priority over the callback queue. Every single time.</p><p>Sources of microtasks:</p><ul><li>Promise.then() / Promise.catch() / Promise.finally() callbacks</li><li>queueMicrotask()</li><li>MutationObserver callbacks</li><li>await (under the hood, it&#39;s a promise)</li></ul><p>The rule is this: <strong>after every task completes (or after the initial script finishes), the entire microtask queue is drained before the next macrotask runs.</strong></p><p>Not one microtask. <em>All of them.</em> And if a microtask schedules another microtask, that one runs too, before any macrotask.</p><pre>console.log(&quot;1 — Script start&quot;);</pre><pre>setTimeout(() =&gt; console.log(&quot;5 — setTimeout&quot;), 0);  // Macrotask</pre><pre>Promise.resolve()<br>    .then(() =&gt; console.log(&quot;3 — Promise 1&quot;))         // Microtask<br>    .then(() =&gt; console.log(&quot;4 — Promise 2&quot;));        // Microtask (scheduled by microtask)</pre><pre>console.log(&quot;2 — Script end&quot;);</pre><pre>// Output:<br>// 1 — Script start<br>// 2 — Script end<br>// 3 — Promise 1<br>// 4 — Promise 2<br>// 5 — setTimeout</pre><p>Even though setTimeout was registered <em>before</em> the Promise chain, it fires <em>after</em> both promise callbacks. The entire microtask queue empties first.</p><h3>6. The Event Loop — The Conductor Tying It All Together</h3><p>The <strong>event loop</strong> is the algorithm that orchestrates all of this. Here it is, in pseudocode:</p><pre>while (true) {<br>    // 1. Run the current task (or the initial script)<br>    executeCurrentTask();</pre><pre>    // 2. Drain the entire microtask queue<br>    while (microtaskQueue.isNotEmpty()) {<br>        microtaskQueue.dequeue().execute();<br>        // Note: if this microtask adds more microtasks, those run too<br>    }</pre><pre>    // 3. Maybe render (browser decides, typically ~60fps)<br>    if (renderingNeeded) {<br>        render();<br>    }</pre><pre>    // 4. Pick the next macrotask from the callback queue<br>    if (callbackQueue.isNotEmpty()) {<br>        currentTask = callbackQueue.dequeue();<br>    }<br>}</pre><p>The loop is always watching. When the call stack is empty and there are tasks waiting, it picks the next one and runs it. But it <em>always</em> drains microtasks first.</p><p>Here’s the full picture as a diagram:</p><pre>┌─────────────────────────────────────────────────┐<br>│                 Your JS Code                    │<br>│                  Call Stack                     │<br>└────────────────────┬────────────────────────────┘<br>                     │<br>           calls Web APIs / Node APIs<br>                     │<br>                     ▼<br>┌─────────────────────────────────────────────────┐<br>│            Web APIs / C++ APIs                  │<br>│   (setTimeout, fetch, fs.readFile, events...)   │<br>└──────┬──────────────────────┬───────────────────┘<br>       │                      │<br>       ▼                      ▼<br>┌─────────────┐      ┌──────────────────┐<br>│  Microtask  │      │  Callback Queue  │<br>│    Queue    │      │  (Macrotask Q.)  │<br>│  (Promises) │      │  (setTimeout,    │<br>│             │      │   I/O, events)   │<br>└──────┬──────┘      └────────┬─────────┘<br>       │                      │<br>       └──────────┬───────────┘<br>                  │<br>                  ▼<br>           ┌──────────────┐<br>           │  Event Loop  │ ◄── &quot;Is the stack empty?<br>           │              │      Drain microtasks.<br>           └──────────────┘      Then run next macrotask.&quot;</pre><h3>7. setTimeout and setInterval — What They Actually Promise</h3><p>setTimeout(fn, delay) does <em>not</em> guarantee your callback runs after exactly delay milliseconds. It guarantees the callback will be added to the macrotask queue <em>no sooner than</em> delay milliseconds from now.</p><p>If the call stack is busy, the callback waits — no matter how long.</p><pre>const start = Date.now();</pre><pre>// This timer should fire after 100ms.<br>setTimeout(() =&gt; {<br>    // In reality, this will log something much larger than 100.<br>    console.log(`Fired after ${Date.now() - start}ms`);<br>}, 100);</pre><pre>// This synchronous loop blocks the call stack for ~500ms.<br>// The setTimeout callback is in the queue, but it can&#39;t run yet.<br>const blockUntil = Date.now() + 500;<br>while (Date.now() &lt; blockUntil) {<br>    // spinning — this is exactly the kind of code that freezes UIs<br>}</pre><pre>// Output: something like &quot;Fired after 502ms&quot; — not 100ms</pre><p>setTimeout(..., 0) is often used as a trick to defer code to the <em>next iteration</em> of the event loop — but it&#39;s still a macrotask, so it yields to all pending microtasks first.</p><h3>8. Promises and the Microtask Queue</h3><p>Every .then(), .catch(), and .finally() callback is a microtask. This is baked into the Promise specification — not a browser decision.</p><pre>console.log(&quot;start&quot;);</pre><pre>const p = new Promise((resolve) =&gt; {<br>    // The executor function runs SYNCHRONOUSLY, right now.<br>    console.log(&quot;inside Promise constructor&quot;);<br>    resolve(&quot;done&quot;);<br>});</pre><pre>p.then((value) =&gt; {<br>    // This runs as a MICROTASK — after the current synchronous code finishes.<br>    console.log(&quot;then:&quot;, value);<br>});</pre><pre>console.log(&quot;end&quot;);</pre><pre>// Output:<br>// start<br>// inside Promise constructor<br>// end<br>// then: done</pre><p>The Promise constructor runs synchronously. The .then() callback does not — it queues as a microtask and runs after the current call stack empties.</p><p>This surprises a lot of developers. They expect the .then() to run right after resolve(). It doesn&#39;t. It politely waits its turn.</p><h3>9. async/await — Syntactic Sugar with Real Consequences</h3><p>async/await is beautiful syntax. But it&#39;s crucial to understand what it compiles to, because the semantics are the same as Promises — just dressed up.</p><pre>// This async function...<br>async function fetchUser(id) {<br>    const response = await fetch(`/api/users/${id}`);<br>    const user = await response.json();<br>    return user;<br>}</pre><pre>// ...is roughly equivalent to this Promise chain:<br>function fetchUser(id) {<br>    return fetch(`/api/users/${id}`)<br>        .then(response =&gt; response.json())<br>        .then(user =&gt; user);<br>}</pre><p>Every await is a suspension point. When you await something, the async function pauses and hands control back to the caller. The code <em>after</em> the await is scheduled as a microtask to run when the awaited Promise resolves.</p><pre>async function main() {<br>    console.log(&quot;1 — before await&quot;);</pre><pre>    await Promise.resolve();  // Suspends here. Resumes as microtask.</pre><pre>    console.log(&quot;3 — after await&quot;);  // Runs as microtask<br>}</pre><pre>main();<br>console.log(&quot;2 — after calling main()&quot;);</pre><pre>// Output:<br>// 1 — before await<br>// 2 — after calling main()<br>// 3 — after await</pre><p>When main() hits the await, it suspends. JavaScript keeps running synchronously past the main() call and logs &quot;2&quot;. Then the microtask runs and logs &quot;3&quot;.</p><p>async/await does <em>not</em> make code run on a different thread. It&#39;s still single-threaded. It just makes asynchronous code <em>look</em> synchronous while still yielding the call stack between operations.</p><h3>10. Real-World Execution Order Puzzles</h3><p>Let’s put it all together. Work through these before peeking at the answers.</p><h3>Puzzle 1</h3><pre>console.log(&quot;A&quot;);</pre><pre>setTimeout(() =&gt; console.log(&quot;B&quot;), 0);</pre><pre>Promise.resolve().then(() =&gt; {<br>    console.log(&quot;C&quot;);<br>    setTimeout(() =&gt; console.log(&quot;D&quot;), 0);<br>});</pre><pre>console.log(&quot;E&quot;);</pre><p>Answer</p><pre>A<br>E<br>C<br>B<br>D</pre><p><strong>Why:</strong></p><ol><li>A — synchronous</li><li>setTimeout B → macrotask queue</li><li>Promise → microtask queue</li><li>E — synchronous</li><li>Call stack empty → drain microtasks: C logs, setTimeout D → macrotask queue</li><li>No more microtasks → run next macrotask: B</li><li>No more microtasks → run next macrotask: D</li></ol><h3>Puzzle 2</h3><pre>async function alpha() {<br>    console.log(&quot;alpha 1&quot;);<br>    await null;<br>    console.log(&quot;alpha 2&quot;);<br>}</pre><pre>async function beta() {<br>    console.log(&quot;beta 1&quot;);<br>    await null;<br>    console.log(&quot;beta 2&quot;);<br>}</pre><pre>console.log(&quot;start&quot;);<br>alpha();<br>beta();<br>console.log(&quot;end&quot;);</pre><p>Answer</p><pre>start<br>alpha 1<br>beta 1<br>end<br>alpha 2<br>beta 2</pre><p><strong>Why:</strong></p><ol><li>start — sync</li><li>alpha() runs: logs alpha 1, hits await, suspends → schedules microtask</li><li>beta() runs: logs beta 1, hits await, suspends → schedules microtask</li><li>end — sync</li><li>Call stack empty → drain microtasks: alpha 2, then beta 2</li></ol><h3>11. Pitfalls That Will Bite You in Production</h3><h3>Starving the render with too many microtasks</h3><p>Because microtasks all run before the browser gets a chance to render, an infinite microtask loop will lock up the UI just as badly as a synchronous loop — possibly worse, because it <em>looks</em> like async code.</p><pre>// ❌ Don&#39;t do this — infinite microtask loop, browser never renders<br>function infiniteMicrotasks() {<br>    Promise.resolve().then(infiniteMicrotasks);<br>}<br>infiniteMicrotasks();</pre><pre>// ✅ If you need to yield to rendering, use setTimeout or requestAnimationFrame<br>function yieldToRender(fn) {<br>    requestAnimationFrame(fn);  // Runs after the next render frame<br>}</pre><h3>Unhandled Promise rejections are silent killers</h3><pre>// ❌ This rejection is unhandled. In older Node versions it silently fails.<br>//    In modern Node, it crashes the process.<br>async function riskyOperation() {<br>    throw new Error(&quot;Something went wrong&quot;);<br>}</pre><pre>riskyOperation(); // Missing await AND missing .catch()</pre><pre>// ✅ Always handle rejections<br>riskyOperation().catch(err =&gt; console.error(&quot;Caught:&quot;, err));</pre><pre>// ✅ Or use try/catch with await<br>try {<br>    await riskyOperation();<br>} catch (err) {<br>    console.error(&quot;Caught:&quot;, err);<br>}</pre><h3>await inside loops — sequential vs parallel</h3><pre>const userIds = [1, 2, 3, 4, 5];</pre><pre>// ❌ Sequential — each fetch waits for the previous to finish.<br>//    Total time: sum of all request times. Slow.<br>async function fetchSequential(ids) {<br>    const results = [];<br>    for (const id of ids) {<br>        const user = await fetchUser(id);  // Waits here before next iteration<br>        results.push(user);<br>    }<br>    return results;<br>}</pre><pre>// ✅ Parallel — all requests fire at once.<br>//    Total time: slowest single request. Fast.<br>async function fetchParallel(ids) {<br>    const promises = ids.map(id =&gt; fetchUser(id));  // Fire all, don&#39;t await yet<br>    return await Promise.all(promises);              // Wait for all to complete<br>}</pre><h3>The forEach async trap</h3><pre>const data = [1, 2, 3];</pre><pre>// ❌ forEach doesn&#39;t await async callbacks. It fires them all and moves on.<br>//    &quot;Done&quot; prints before any of the async work finishes.<br>data.forEach(async (item) =&gt; {<br>    await processItem(item);<br>});<br>console.log(&quot;Done&quot;);  // Prints immediately — not actually done</pre><pre>// ✅ Use for...of when you need to await inside a loop<br>for (const item of data) {<br>    await processItem(item);<br>}<br>console.log(&quot;Done&quot;);  // Now actually done</pre><h3>12. Conclusion — The Mental Model You’ll Keep Forever</h3><p>Here’s the mental model, distilled:</p><p><strong>JavaScript has one thread, one call stack.</strong> It can only do one thing at a time. Async operations — timers, network calls, I/O — get delegated to the browser/Node runtime, which handles them off the main thread. When they complete, callbacks get queued.</p><p><strong>Two queues exist.</strong> The microtask queue (Promises, await) and the macrotask queue (setTimeout, I/O, events). After every task — including the initial script — the entire microtask queue drains before the next macrotask runs.</p><p><strong>async/await is Promises in a costume.</strong> Beautiful, readable, but the same underlying semantics. Every await suspends the function and schedules the rest as a microtask.</p><p>Once this model clicks, async JavaScript stops being magic. You can trace any execution order in your head. You know why setTimeout(..., 0) doesn&#39;t always mean &quot;immediately.&quot; You know why a Promise resolves after your synchronous code. You know why that forEach with await inside was never actually doing what you thought.</p><p>The event loop is the heartbeat of JavaScript. Understanding it doesn’t just make you better at debugging async bugs — it makes you better at writing async code in the first place. You start structuring things around how JavaScript <em>actually</em> works, rather than how you wish it worked.</p><p>Go write something async. Then trace through it mentally. If you get the order right — you’ve got it.</p><p><em>Further reading: MDN’s </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop"><em>Concurrency model and the event loop</em></a><em>, Jake Archibald’s classic talk “In The Loop” (JSConf Asia), and the WHATWG HTML spec on the </em><a href="https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model"><em>event loop processing model</em></a><em> if you really want to go deep.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4982f45545d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>