# Last updated: 2026-12-05 # Pankaj Kumar Code explorations, engineering thoughts, and life in between. Index (summary of all pages): https://pankaj.xyz/llms.txt ## Posts # Serverless, Dependency-Free Article Upvote System for Static Sites Source: https://pankaj.xyz/posts/serverless-dependency-free-article-upvote-system-for-static-sites/serverless-dependency-free-article-upvote-system-for-static-sites.md *Anonymous per-device votes, one serverless function and one Postgres database. No framework required, no npm packages.* Static sites are fast, cheap and hard to break, but the moment you want a live upvote counter you need somewhere to keep state. This post walks through a small upvote system I built for my blog, which is a static site on [Cloudflare Pages](https://pages.cloudflare.com/). Nothing in it depends on a particular site generator: the page side is one HTML snippet, one script and some CSS, and the server side is one function plus three Postgres tables. It was inspired by [Herman's Bear Blog](https://herman.bearblog.dev/) and [Betaveros's deep-dive "That Accursed Upvote Button"](https://betaveros.bearblog.dev/that-accursed-upvote-button/), which are both worth reading for the tradeoffs involved. By the end you will have: - three tables on [Neon](https://neon.com/) (any Postgres 12 or newer works), - one serverless function (about 330 lines of plain JavaScript, including comments), - one HTML snippet, one small client script and a bit of CSS. The code in this post is complete. File names are only suggestions, so put things wherever your project layout prefers and adjust the paths in the ` ``` What each part is for: - **`data-id`** is the post's vote ID, and **`data-api`** is the function's URL. Both are read by the script. - **The honeypot** is a text field a human never sees. The page ships it pre-filled, the script empties it on the first genuine mouse, touch or key event, and the server rejects any vote that arrives with it still filled. That catches scripts that replay the form without interacting. It is a speed bump, not protection. The field name is arbitrary (here it is called `title`), but the markup, the script and the function must all agree on it, so change them together. - **`data-state="loading"`** on the count starts it invisible, with its space reserved, so there is no flash of a wrong number. - **The `upvote-label` span** must stay: the script puts failure messages there for a few seconds. - **`data-title` and the `.custom-tooltip` lookup** in the script are hooks for a custom tooltip component. If you use a plain `title` attribute or no tooltip, you can delete them. ### The client script Save this as `static/js/upvote-client.js`, or wherever your site serves scripts from. ```javascript // static/js/upvote-client.js // Client-side upvote handler (runs in the reader's browser). // // - The server is the source of truth. The UI updates optimistically on click // and is rolled back if the vote is not confirmed. // - The count stays hidden until the server has reported it, so a stale "0" is // never shown. No optimistic +1 happens while the count is unknown. // - Errors are shown in the button label for a few seconds (works on touch // screens, where tooltips do not) and announced to screen readers via // .upvote-status. The button is disabled while the error is showing. // - The anonymous voter token and the "already upvoted" flag live in // localStorage, with an in-memory fallback when storage is unavailable. // - The honeypot field is pre-filled by the template and cleared on real user // interaction; bots that never interact send it filled and are rejected. (function () { 'use strict'; const DWELL_MS = 1500; // votes are sent no earlier than this after page load const MESSAGE_MS = 3000; // how long an error shows (the button is disabled meanwhile) const STATUS_MS = 5000; // how long the screen-reader message stays in the DOM const TOKEN_RE = /^vtr_[a-f0-9]{32}$/; const TEXT = { idle: 'Upvote this article', voted: 'You upvoted this article', // label: shown inside the button; message: announced to screen readers only limited: { label: 'Try again later', message: 'Please try again later.' }, failed: { label: 'Upvote failed', message: 'Please try again later.' }, }; // localStorage that never throws (Safari private mode, blocked storage, ...). const store = (() => { const mem = {}; return { get(key) { try { const v = window.localStorage.getItem(key); if (v !== null) return v; } catch (_) { /* fall through to memory */ } return Object.prototype.hasOwnProperty.call(mem, key) ? mem[key] : null; }, set(key, value) { mem[key] = value; try { window.localStorage.setItem(key, value); } catch (_) { /* memory fallback only */ } }, remove(key) { delete mem[key]; try { window.localStorage.removeItem(key); } catch (_) { /* ignore */ } }, }; })(); function randomHex(byteCount) { const bytes = new Uint8Array(byteCount); if (window.crypto && typeof window.crypto.getRandomValues === 'function') { window.crypto.getRandomValues(bytes); } else { for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256); } return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); } // Persistent anonymous device token: "vtr_" + 32 hex chars (the format the // server validates). Anything stored in an older format is replaced. function getVoterToken() { let token = store.get('voter_token'); if (!token || !TOKEN_RE.test(token)) { token = 'vtr_' + randomHex(16); store.set('voter_token', token); } return token; } function initUpvote() { const form = document.getElementById('upvote-form'); const btn = document.getElementById('upvote-btn'); const countEl = document.getElementById('upvote-count'); if (!form || !btn || !countEl) return; const postId = form.dataset.id; const apiUrl = form.dataset.api; if (!postId || !apiUrl) { console.warn('upvote: missing data-id or data-api on #upvote-form'); return; } const labelEl = btn.querySelector('.upvote-label'); const statusEl = form.querySelector('.upvote-status'); const idleLabelText = labelEl ? labelEl.textContent : ''; const storageKey = 'upvoted_' + postId; const honeypot = form.querySelector('input[name="title"]'); const voterToken = getVoterToken(); const pageLoadTime = Date.now(); let inFlight = false; // a vote request is pending let votedThisSession = false; // the server confirmed a vote in this page view let currentCount = null; // null until the server has told us let cooldown = false; // an error is showing; the button is disabled let messageTimer = null; let statusTimer = null; // ---- count ------------------------------------------------------------ // data-state drives the CSS: loading (hidden, space reserved), ready, // unavailable (hidden, no space). function renderCount(n) { currentCount = n; countEl.textContent = String(n); countEl.dataset.state = 'ready'; } function markCountUnavailable() { if (currentCount === null) countEl.dataset.state = 'unavailable'; } countEl.textContent = ''; countEl.dataset.state = 'loading'; // ---- label / tooltip / screen-reader text ------------------------------ // Keep the custom tooltip text in sync if it is currently showing. function syncVisibleTooltip(text) { const tooltipEl = document.querySelector('.custom-tooltip'); if (tooltipEl && tooltipEl.classList.contains('visible')) tooltipEl.textContent = text; } function setLabel(text) { btn.setAttribute('data-title', text); btn.setAttribute('aria-label', text); btn.removeAttribute('title'); syncVisibleTooltip(text); } function setStatus(text) { if (!statusEl) return; clearTimeout(statusTimer); statusEl.textContent = text; statusTimer = setTimeout(() => { statusEl.textContent = ''; }, STATUS_MS); } function setUpvotedState(isUpvoted) { if (isUpvoted) { btn.classList.add('upvoted'); btn.setAttribute('aria-pressed', 'true'); btn.setAttribute('aria-disabled', 'true'); setLabel(TEXT.voted); } else { btn.classList.remove('upvoted'); btn.removeAttribute('aria-pressed'); if (cooldown) btn.setAttribute('aria-disabled', 'true'); else btn.removeAttribute('aria-disabled'); setLabel(TEXT.idle); } } // Show an error inside the button for a few seconds and announce it to // screen readers. The tooltip is left alone. The button is disabled // (aria-disabled keeps keyboard focus) so it cannot be spammed meanwhile. function showError(err) { clearTimeout(messageTimer); cooldown = true; btn.setAttribute('aria-disabled', 'true'); if (labelEl) labelEl.textContent = err.label; setStatus(err.message); messageTimer = setTimeout(clearError, MESSAGE_MS); } function clearError() { clearTimeout(messageTimer); cooldown = false; if (labelEl) labelEl.textContent = idleLabelText; if (!btn.classList.contains('upvoted')) btn.removeAttribute('aria-disabled'); } // ---- honeypot ---------------------------------------------------------- // Cleared only by real user interaction. const clearHoneypot = () => { if (honeypot) honeypot.value = ''; }; ['mousemove', 'touchstart', 'keydown', 'pointerdown'].forEach((evt) => window.addEventListener(evt, clearHoneypot, { once: true, passive: true }) ); // Instant UI from the local flag; the server reconciles it below. setUpvotedState(store.get(storageKey) === 'true'); // ---- initial load ------------------------------------------------------ // Fetch the live count and reconcile with the server. Non-blocking. function loadState() { const url = apiUrl + '?id=' + encodeURIComponent(postId) + '&voterToken=' + encodeURIComponent(voterToken); fetch(url, { headers: { Accept: 'application/json' } }) .then((res) => (res.ok ? res.json() : null)) .then((data) => { // This response may have been computed before the user's vote. Once a // vote is in flight or confirmed, the POST result owns the UI. if (inFlight || votedThisSession) return; if (!data || typeof data.count !== 'number') { markCountUnavailable(); return; } renderCount(data.count); if (data.hasVoted) { store.set(storageKey, 'true'); setUpvotedState(true); } else { store.remove(storageKey); setUpvotedState(false); } }) .catch(() => { // Offline or API unavailable: keep whatever the UI shows. if (!inFlight && !votedThisSession) markCountUnavailable(); }); } if ('requestIdleCallback' in window) { window.requestIdleCallback(loadState, { timeout: 2000 }); } else { setTimeout(loadState, 0); } // ---- voting ------------------------------------------------------------ function rollback(previousCount, data) { setUpvotedState(false); if (data && typeof data.count === 'number') renderCount(data.count); else if (previousCount !== null) renderCount(previousCount); } function sendVote(previousCount) { fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: postId, voterToken: voterToken, title: honeypot ? honeypot.value : '', // must be empty }), }) .then((res) => res .json() .catch(() => null) .then((data) => ({ ok: res.ok, status: res.status, data })) ) .then(({ ok, status, data }) => { inFlight = false; if (ok && data && data.hasVoted) { // 'voted' or 'duplicate' (already voted on this device): either // way the server has the vote. Use its authoritative count. if (typeof data.count === 'number') renderCount(data.count); votedThisSession = true; store.set(storageKey, 'true'); setUpvotedState(true); setStatus(TEXT.voted); return; } rollback(previousCount, data); showError(status === 429 ? TEXT.limited : TEXT.failed); }) .catch(() => { inFlight = false; rollback(previousCount, null); showError(TEXT.failed); }); } btn.addEventListener('click', (e) => { e.preventDefault(); // Ignore script-generated clicks (element.click() from a bot). Assistive // technology and keyboard activation are trusted events and still work. if (!e.isTrusted) return; if (inFlight || cooldown || btn.classList.contains('upvoted')) return; clearHoneypot(); inFlight = true; // Optimistic update. Only bump the number if we actually know it. const previousCount = currentCount; setUpvotedState(true); if (previousCount !== null) renderCount(previousCount + 1); // Dwell-time bot trap: an early click is not dropped, it is sent once // DWELL_MS has passed since page load. const wait = Math.max(0, DWELL_MS - (Date.now() - pageLoadTime)); setTimeout(() => sendVote(previousCount), wait); }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initUpvote, { once: true }); } else { initUpvote(); } })(); ``` What the script takes care of: - **Instant first paint, then reconciliation.** It shows the remembered state immediately, then asks the server and corrects anything that disagrees. Requests are deferred with `requestIdleCallback`, so the page never waits on them. - **Optimistic voting with rollback.** The click updates the button at once. If the server doesn't confirm, the count and button go back and the button shows `Try again later` (for a `429`) or `Upvote failed` for a few seconds, disabled so it can't be hammered. - **No misleading numbers.** The count is hidden until the server reports it, and a click before that doesn't invent a "+1". - **Stale responses are ignored.** If the initial `GET` arrives after the user has already voted, it can't overwrite the confirmed result. - **Three cheap speed bumps.** The honeypot field, a 1.5 second minimum between page load and the request (an early click is delayed, not dropped), and a check that the click is a real user event rather than a script calling `element.click()`. - **Storage that can fail.** Private modes and blocked storage fall back to memory instead of breaking the page, and tokens in an unexpected format are replaced. ### The styles Add this to your stylesheet. The custom properties have fallbacks, so it works as is, and you can map them to your own theme tokens. ```css /* Upvote component */ .upvote-container { display: flex; justify-content: center; margin: 2.5rem 0 0.5rem; } /* Without JavaScript the button cannot work, so do not show it. */ @media (scripting: none) { .upvote-container { display: none; } } .upvote-button { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.45rem 1rem; font: inherit; font-weight: 500; color: var(--color-text-secondary, #555); background-color: var(--color-bg-subtle, #f5f5f5); border: 2px solid var(--color-border, #d0d0d0); border-radius: 999px; cursor: pointer; user-select: none; transition: background-color 0.15s, border-color 0.15s, color 0.15s, transform 0.15s; } /* Hover styles only on devices that really hover. On touch screens :hover sticks after a tap, which would make a rolled-back vote look upvoted. */ @media (hover: hover) { .upvote-button:hover:not(.upvoted):not([aria-disabled="true"]) { color: var(--color-text, #111); background-color: var(--color-accent-subtle, #e8f0ff); border-color: var(--color-accent, #3366ff); transform: translateY(-1px); } } .upvote-button:focus-visible { outline: 2px solid var(--color-accent, #3366ff); outline-offset: 2px; } .upvote-icon svg { width: 18px; height: 18px; display: block; } .upvote-count { display: inline-flex; align-items: center; justify-content: center; min-width: 1.5rem; height: 1.5rem; padding: 0 0.4rem; font-size: 0.75rem; font-weight: 600; font-variant-numeric: tabular-nums; color: var(--color-text-secondary, #555); background-color: var(--color-border, #d0d0d0); border-radius: 999px; box-shadow: inset 0 0 0 1px transparent; transition: all 0.15s; } /* Count states, set by the script via data-state: loading - the server has not answered yet: invisible, space reserved ready - show the number unavailable - the count could not be loaded: hide the chip entirely */ .upvote-count[data-state="loading"] { opacity: 0; } .upvote-count[data-state="unavailable"] { display: none; } @media (hover: hover) { .upvote-button:hover:not(.upvoted):not([aria-disabled="true"]) .upvote-count { color: var(--color-text, #111); background-color: var(--color-bg, #fff); box-shadow: inset 0 0 0 1.5px var(--color-accent, #3366ff); } } .upvote-button.upvoted .upvote-count { color: var(--color-text, #111); background-color: var(--color-bg, #fff); box-shadow: inset 0 0 0 1.5px var(--color-accent, #3366ff); } .upvote-button.upvoted { color: var(--color-text, #111); background-color: var(--color-accent-subtle, #e8f0ff); border-color: var(--color-accent, #3366ff); cursor: default; transform: none; } /* Disabled for a few seconds while an error message is showing. */ .upvote-button[aria-disabled="true"]:not(.upvoted) { cursor: not-allowed; } /* Screen-reader-only live region for vote results and errors. */ .upvote-status { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } /* Honeypot: out of the layout and the accessibility tree. The extra .upvote-form in the selector out-ranks a global .sr-only rule, so no !important is needed. The script can still read its value. */ .upvote-form .upvote-honeypot { display: none; } /* Respect reduced-motion preferences. Keep this block last so it wins. */ @media (prefers-reduced-motion: reduce) { .upvote-button, .upvote-count { transition: none; } .upvote-button:hover:not(.upvoted):not([aria-disabled="true"]) { transform: none; } } ``` ## Step 4: Wire it into your site The only site-specific part is producing a stable ID for each post and printing it into `data-id`, plus rendering the snippet on post pages. ### Choosing the post ID The ID can be any string that identifies a post and never changes. The post's path works well, for example `posts/hello-world`. - The function strips leading and trailing slashes, so `/posts/hello-world/` and `posts/hello-world` are the same post. - Allowed characters are letters, digits, `.`, `_`, `~` and `-`, in up to six `/`-separated segments that each start with a letter or digit, 200 characters at most. If a slug contains anything else, such as spaces or non-ASCII characters, give that post an explicit ID. - Most generators expose the path directly. For example: `page.path` in Zola, `.RelPermalink` in Hugo, `page.url` in Jekyll and Eleventy, and `Astro.url.pathname` in Astro. Check your generator's docs for the exact output; what matters is that it stays the same for a given post. To survive renames, add an optional front-matter field (I call mine `uid`) and prefer it when it is set: ```text data-id = post.uid, if set; otherwise the post's path ``` If you later rename a post's slug, set `uid` to the **old** ID. Votes are keyed on that string, so they follow the post. ### Where to render it Render the snippet only on post pages, after the article body, and load the script with `defer` on those same pages. If you want a per-post opt-out, a front-matter flag such as `upvote: false` that your template checks before rendering both the snippet and the ` ``` ## 4. Exposing Raw Markdown Pages This is the most impactful change. I wrote `scripts/copy_md_files.py` to mirror the entire `content/` directory into `public/` as raw `.md` files during the build. Zola renders `my-post.md` into `public/my-post/index.html` so the URL is `https://yoursite.com/my-post/`. The script places the original Markdown file at `public/my-post/my-post.md`. An AI hitting the HTML page can effortlessly request the `.md` sibling at a predictable, consistent URL - no parsing required. The script reads and respects the TOML frontmatter: draft pages are skipped, so only published content gets mirrored. ```python # scripts/copy_md_files.py import os import shutil import re import sys from pathlib import Path try: import tomllib except ModuleNotFoundError: import tomli as tomllib def parse_frontmatter(content: str) -> dict: match = re.match(r"^\+\+\+\s*\n(.*?)\n\+\+\+", content, re.DOTALL) if not match: return {} try: return tomllib.loads(match.group(1)) except Exception: return {} def copy_md_files(): project_root = Path(__file__).parent.parent content_dir = project_root / "content" public_dir = project_root / "public" if not public_dir.exists(): print("Error: public directory does not exist. Run zola build first.") sys.exit(1) copied = 0 for md_file in content_dir.rglob("*.md"): if md_file.name == "_index.md": continue content = md_file.read_text(encoding='utf-8') fm = parse_frontmatter(content) # Skip drafts if fm.get("draft") == True: continue slug = fm.get("slug") if not slug: if md_file.name == "index.md": slug = md_file.parent.name else: slug = md_file.stem rel_path = md_file.relative_to(content_dir) if md_file.name == "index.md": if rel_path.parent.name == slug: output_dir = public_dir / rel_path.parent else: output_dir = public_dir / rel_path.parent / slug else: if rel_path.parent == Path("."): output_dir = public_dir / slug else: output_dir = public_dir / rel_path.parent / slug output_path = output_dir / f"{slug}.md" output_dir.mkdir(parents=True, exist_ok=True) # Read the raw bytes and prepend a UTF-8 BOM if missing. # This forces LLM crawlers and browsers to decode the file as UTF-8 # (fixing corrupted characters like ├──) even without HTTP charset headers. raw_bytes = md_file.read_bytes() if not raw_bytes.startswith(b'\xef\xbb\xbf'): raw_bytes = b'\xef\xbb\xbf' + raw_bytes output_path.write_bytes(raw_bytes) shutil.copystat(md_file, output_path) print(f"Copied {md_file.relative_to(project_root)} to {output_path.relative_to(project_root)}") copied += 1 print(f"Successfully copied {copied} markdown files.") if __name__ == "__main__": copy_md_files() ``` ## 5. Creating the llms.txt and llms-full.txt Indexes `/llms.txt` is an emerging convention for websites to provide AI models with a curated index of available content - think `sitemap.xml` but designed for LLM consumption rather than search engine crawlers. I created two Zola templates that generate these files dynamically from the site's actual published pages. **`templates/llms.html`** - the index: ```jinja2 # Last updated: {{ now() | date(format="%Y-%m-%d") }} # {{ config.title | safe }} {{ config.description | safe }} Full corpus (all pages, one document): {{ config.base_url | safe }}llms-full.txt ## Pages {% for section_name in config.extra.featured_sections %} {% set sec = get_section(path=section_name ~ "/_index.md") %} {% for page in sec.pages %} {% if page.draft %}{% continue %}{% endif %} - [{{ page.title }}]({{ page.permalink }}){% if page.description %} - {{ page.description }}{% endif %} {% endfor %} {% endfor %} ``` **`templates/llms-full.html`** - the full corpus. This one uses a small trick: `load_data` fetches the raw file from disk, then `split(pat="+++")` breaks it on the TOML delimiters. TOML frontmatter is wrapped in two `+++` fences, which means splitting on `+++` gives three parts: an empty string before the first fence, the frontmatter itself, and the Markdown body. `parts[2:]` therefore skips the first two parts and leaves only the body content. ```jinja2 # Last updated: {{ now() | date(format="%Y-%m-%d") }} # {{ config.title | safe }} {{ config.description | safe }} Index (summary of all pages): {{ config.base_url | safe }}llms.txt {% for section_name in config.extra.featured_sections %} {% set sec = get_section(path=section_name ~ "/_index.md") %} {% for page in sec.pages %} {% if page.draft %}{% continue %}{% endif %} # {{ page.title }} Source: {{ page.permalink }} {% set raw_content = load_data(path=page.relative_path) %} {% set parts = raw_content | split(pat="+++") %} {% set raw_markdown = parts[2:] | join(sep="+++") %} {{ raw_markdown | trim }} {% endfor %} {% endfor %} ``` These templates are powered by two simple content files - `content/llms/index.md` and `content/llms-full/index.md` - that do nothing except point to their respective templates. ## 6. Fixing the File Extensions in the Build Process Zola's output model is folder-per-page: `llms.md` becomes `public/llms.txt/index.html` (if the slug is `llms.txt`). The files need to land at `public/llms.txt` and `public/llms-full.txt` as plain files, not directories. I handle this in `build.sh` post-Zola: ```bash echo ">>> Fixing AI index filenames..." # llms.txt mv public/llms.txt/index.html public/llms_tmp.txt && \ rm -rf public/llms.txt && \ mv public/llms_tmp.txt public/llms.txt # llms-full.txt mv public/llms-full.txt/index.html public/llms-full_tmp.txt && \ rm -rf public/llms-full.txt && \ mv public/llms-full_tmp.txt public/llms-full.txt ``` Using `&&` here is intentional: if the initial `mv` fails (e.g., the file was never generated), the script stops rather than running `rm -rf` on the directory and silently losing your previous output. I mirrored this logic in the `Makefile` target for local development so the local build always matches production. > **Note:** I use Cloudflare Pages to deploy my website. ## 7. The Final Directory Structure After running the full build pipeline - `zola build`, then `copy_md_files.py`, then the filename fixups - `public/` looks like this: ```text public/ ├── index.html ← Standard Zola homepage ├── sitemap.xml ← Standard Zola sitemap ├── robots.txt ← Updated with LLMs/LLMs-full entries ├── llms.txt ← AI index (renamed from directory by build.sh) ├── llms-full.txt ← AI corpus (renamed from directory by build.sh) └── my-post/ ├── index.html ← Standard Zola HTML post └── my-post.md ← Raw Markdown injected by copy_md_files.py ``` Each post directory ends up with both representations side by side. The HTML page announces the Markdown sibling via `` in the `
`, so any crawler that inspects head tags can find the clean version immediately. --- ## Conclusion Most static sites are technically accessible to AI crawlers but practically difficult to parse. Noisy HTML, missing structured metadata, and no predictable Markdown endpoint all create friction that degrades the quality of AI-generated answers citing your content. With these seven changes - an HTML directive, an updated `robots.txt`, semantic head tags, Markdown mirroring, dynamically generated `llms.txt` and `llms-full.txt`, and build-time fixups - the site now speaks the language AI agents actually prefer. The implementation adds no runtime overhead (everything is generated at build time) and degrades gracefully: every change is purely additive and leaves the human-facing site untouched. Flush! # Sad state of affairs for India's IT Services Industry Source: https://pankaj.xyz/posts/sad-state-of-affairs-for-indias-it-services-industry/sad-state-of-affairs-for-indias-it-services-industry.md ## How the IT service sector found the perfect excuse in AI Ten years in this industry - across product companies where engineering was treated like a craft, and service companies where it was treated like inventory - has taught me one uncomfortable truth: most IT service organizations never saw developers as developers. We were `resources`, billable, fungible, disposable resources. > AI didn't create this mindset. It just gave management a new vocabulary to justify it. ## The Resource Economy In a resource economy, nobody asks if the work is good. They ask if the work is *fast enough* and *cheap enough*. `Deliver more in less time` has been the unofficial company motto since long before anyone in the C-suite could spell `LLM`. Sprints got shorter, scope got bigger, and the gap between the two was always filled by the same thing: a developer's personal time, and eventually, their patience for the job itself. Management, meanwhile, has rarely led - it has *followed*. Whatever term was trending at the last conference became the theme of the next town hall, regardless of whether it fit the actual problem in front of the team. Agile, then hyper-agile, then "we're basically a startup now," then digital transformation, then cloud-native everything - `a parade of buzzwords`, each one arriving at the direct expense of a developer's time, respect, and sanity. Client happiness was the only KPI that ever mattered. Developer wellbeing was a line item nobody wanted to own. > AI is simply the newest costume on the same old mannequin. ## "Anyone Can Code" - Said No One Who Actually Codes The most tiresome line to come out of this AI moment is the confident, faux-progressive declaration from leadership: *"Anyone can code now. You don't even need to be technical."* > It's a convenient thing to say - `if you're not the one being asked to prove it`. If coding were truly that trivial, **HR wouldn't need developers to build the HR portal**. **Finance wouldn't need engineers to fix the billing script**. The same leadership team repeating this line in every all-hands doesn't even **try** to open a code editor themselves. The claim isn't a technical observation - *it's a rhetorical tool*. Once an organization declares that `anyone can code`, it has quietly given itself `permission` to stop valuing the people who do. Your work stops being **engineering** and starts being just another checkbox, because *if anyone could've done it, then what you delivered was never special to begin with*. That's not a technology shift. That's a designed insult. ## The AI Town Hall Problem Every town hall now opens with `"AI"` and closes with `"AI."` Every tagline has been rewritten to squeeze the word in somewhere, whether or not it changes anything about *how the company actually operates*. Cough or sneeze and someone will find a way to relabel it as an `"AI-powered initiative."` This isn't strategy. It's **optics** - a company trying to look relevant to clients and investors, using its own engineering workforce as the backdrop for a slide nobody in leadership actually understands. And the cost of that optics campaign always lands on the same desk: the developer's. ## Harder Growth, Sold as Progress Here's where it stops being annoying and starts being damaging: under the banner of AI, performance bars are quietly being raised while timelines are being cut. The logic, as it's been explained in more than one review cycle, is simple - *"AI makes you faster, so you should be delivering more. And besides, apparently anyone can code now, so the bar for 'exceptional' just went up."* > It's a closed loop that management built for itself: **first devalue the skill publicly, then use that devaluation to justify tougher promotion criteria and thinner growth paths**. Both moves cost the company nothing. Both moves cost the developer everything. ## Elephant in the room AI is not here to turn developers into people who are simply good at writing polite English prompts, no matter how badly the AI industry wants to sell that story. And they *do* want to sell it - every AI company right now has a vested interest in convincing the market that software development as we know it is over, that agents and prompts and loops are the entire future, that `SDLC` is a relic. It's a good pitch if you're trying to be indispensable for the next decade. Companies chasing every sector at once, launching a new **AI for this and that** product every week, aren't doing that because the technology or the market demands it - they're doing it so that when the hype eventually cools and settles down, they're not left irrelevant in a single market they never diversified out of. ## My Actual Take on AI Here's where I'll push back on the doom, because I don't think AI is the villain here - I think it's being *used* as one. > When calculators arrived, they didn't replace accountants. They became a wingman - something that removed the tedious arithmetic so the accountant could focus on judgment, on advising, on the parts of the job that actually required a human. Nobody declared *"anyone can do accounting now"* just because a calculator could add numbers. So no - coding isn't over, and neither is `SDLC`. A prompt doesn't understand your business logic. It doesn't know your users, your edge cases, your compliance constraints, or the five-year-old architectural decision that's still quietly load-bearing. Someone who wasn't a strong developer before AI won't magically become one now, and someone who genuinely couldn't code before still can't, just with better autocomplete. What AI actually demands is more human judgment, not less - a human in the loop who understands *why*, not just *what*. The tragedy is that *service-based companies were never built to value that kind of human*. They were built to value throughput. And if this AI bet doesn't pay off the way leadership is promising the clients, the response won't be introspection - **it'll be a new hiring post**, replacing the very team that was told it was replaceable, without so much as a pause. We were never `developers` to this system. We were always just `resources`. AI didn't change that. It just gave them a more fashionable word for it. Flush! # Setting Up a Highly Available Pi-hole DNS Cluster with Keepalived Source: https://pankaj.xyz/posts/highly-available-pi-hole-dns-cluster-with-keepalived/highly-available-pi-hole-dns-cluster-with-keepalived.md ## Background If you're running Pi-hole as the DNS resolver for your home network, you've probably run into the obvious single point of failure: when that one Raspberry Pi goes down for an update, a reboot, or an SD card failure, every device on your network loses DNS resolution. No DNS, no internet - even devices that don't rely on Pi-hole for ad-blocking still need it to resolve hostnames. The fix is to run two Pi-hole nodes in an **active-active high-availability cluster**, using **keepalived** and the VRRP protocol to manage automatic failover between them. This post walks through exactly how to set that up. > **Note:** None of this is Raspberry Pi-specific. Any pair of machines running a Debian-based OS works - old laptops, mini PCs, VMs, whatever you have lying around. I have used a pair of Raspberry Pi 4Bs (1GB RAM) running DietPi OS, but the steps translate directly to any Debian/Ubuntu-based setup. --- ## The Core Idea Instead of pointing your router at a single Pi-hole IP, you create two **Virtual IPs (VIPs)** - floating addresses that keepalived moves between nodes automatically. Each node is the preferred owner ("master") of one VIP and acts as the backup for the other. That gives you: - **Active-active load distribution** - both nodes handle real traffic under normal conditions, since your router's primary and secondary DNS point at different VIPs. - **Automatic failover** - if one node's Pi-hole service (or the node itself) goes down, its peer detects the failure and takes over both VIPs within seconds. - **No manual intervention** - VRRP handles election and failback automatically, including a configurable delay before a recovered node reclaims its VIP, avoiding flapping. ## Example Network Layout | Role | Hostname | Static IP | Owns VIP (Master) | Backs Up VIP | |---|---|---|---|---| | Node 1 | `dns1` | `192.168.0.10` | `192.168.0.12` (VIP1) | `192.168.0.13` (VIP2) | | Node 2 | `dns2` | `192.168.0.11` | `192.168.0.13` (VIP2) | `192.168.0.12` (VIP1) | On your router, set: - **Primary DNS** → `192.168.0.12` - **Secondary DNS** → `192.168.0.13` Both VIPs are always reachable - they just live on whichever node currently holds them. --- ## Prerequisites - Two machines running a Debian-based OS (Raspberry Pi, mini PC, VM - anything works), each with a static IP reserved on your router - Pi-hole installed and configured identically on both nodes (blocklists, upstream DNS, etc. - use Pi-hole's Teleporter export/import to keep them in sync) - Root/sudo access on both nodes --- ## Step 1: Create a Health-Check DNS Record Keepalived needs a reliable way to verify that DNS resolution is actually *working* on a node - not just that the `pihole-FTL` process is running. The cleanest way to do this is to create a local DNS record that keepalived can query on every health check. In the Pi-hole web UI, go to **Settings → Local DNS → DNS Records** and add: | Domain | IP Address | |---|---| | `dns-probe.internal` | `127.0.0.1` | Repeat this on **both nodes**. Keepalived's health check script will query this record locally; if it stops resolving, the node's VRRP priority drops and its peer takes over. > `.internal` is an IANA-reserved TLD for private use, making it a safe choice for local-only records that should never leak upstream. --- ## Step 2: Install Keepalived Run this on **both nodes**: ```bash sudo apt install keepalived sudo useradd -r -s /sbin/nologin keepalived_script ``` The dedicated `keepalived_script` user is used to run health-check scripts with reduced privileges, per keepalived's script-security model. --- ## Step 3: Configure Each Node Each node runs **two VRRP instances** - one where it's the preferred master, and one where it's a pure backup. This is what creates the active-active effect: both VIPs are "live" somewhere on the network at all times, and each node is actively serving one of them. > **Important:** **Change the `auth_pass` value** on both configs mentioned below to a unique shared secret before deploying. You can generate one with `openssl rand -base64 6`. ### Node 1 `/etc/keepalived/keepalived.conf` ```bash global_defs { router_id DNS1 enable_script_security max_auto_priority script_user keepalived_script } # Health check: verify pihole-FTL is running AND DNS resolves vrrp_script chk_dns { script "/bin/sh -c '/usr/bin/pgrep pihole-FTL > /dev/null && /usr/bin/dig -4 +short +tries=1 +timeout=2 dns-probe.internal @127.0.0.1 | grep -q .'" interval 5 # Run check every 5 seconds timeout 4 # Fail if check takes longer than 4 seconds weight -20 # Subtract 20 from priority on failure fall 2 # Require 2 consecutive failures before marking DOWN rise 2 # Require 2 consecutive successes before marking UP } # VIP1 - preferred owner, reclaims after 60s on recovery vrrp_instance DNS_VIP1 { state BACKUP # Must be BACKUP for preempt_delay to work interface eth0 virtual_router_id 51 priority 100 # Higher priority = wins master election advert_int 1 preempt_delay 60 # Wait 60s after boot before asserting MASTER unicast_src_ip 192.168.0.10 unicast_peer { 192.168.0.11 # Send VRRP packets directly (avoids multicast issues) } authentication { auth_type PASS auth_pass CHANGE_ME } virtual_ipaddress { 192.168.0.12/24 } track_script { chk_dns } } # VIP2 - true backup, never preempts the other node vrrp_instance DNS_VIP2 { state BACKUP interface eth0 virtual_router_id 52 priority 90 advert_int 1 nopreempt # Never reclaim - the peer is the preferred owner of VIP2 unicast_src_ip 192.168.0.10 unicast_peer { 192.168.0.11 } authentication { auth_type PASS auth_pass CHANGE_ME } virtual_ipaddress { 192.168.0.13/24 } track_script { chk_dns } } ``` ### Node 2 `/etc/keepalived/keepalived.conf` Node 2's config is a mirror image: it's the preferred owner of VIP2 and the backup for VIP1. ```bash global_defs { router_id DNS2 enable_script_security max_auto_priority script_user keepalived_script } vrrp_script chk_dns { script "/bin/sh -c '/usr/bin/pgrep pihole-FTL > /dev/null && /usr/bin/dig -4 +short +tries=1 +timeout=2 dns-probe.internal @127.0.0.1 | grep -q .'" interval 5 timeout 4 weight -20 fall 2 rise 2 } # VIP1 - true backup, never preempts Node 1 vrrp_instance DNS_VIP1 { state BACKUP interface eth0 virtual_router_id 51 priority 90 advert_int 1 nopreempt unicast_src_ip 192.168.0.11 unicast_peer { 192.168.0.10 } authentication { auth_type PASS auth_pass CHANGE_ME } virtual_ipaddress { 192.168.0.12/24 } track_script { chk_dns } } # VIP2 - preferred owner, reclaims after 60s on recovery vrrp_instance DNS_VIP2 { state BACKUP interface eth0 virtual_router_id 52 priority 100 advert_int 1 preempt_delay 60 unicast_src_ip 192.168.0.11 unicast_peer { 192.168.0.10 } authentication { auth_type PASS auth_pass CHANGE_ME } virtual_ipaddress { 192.168.0.13/24 } track_script { chk_dns } } ``` ### A few design notes worth calling out - **`state BACKUP` on both instances, on both nodes** - this looks counterintuitive, but it's required for `preempt_delay` to work correctly. Priority determines who actually wins the election. - **`nopreempt` vs `preempt_delay`** - these are mutually exclusive per instance. The preferred-owner instance uses `preempt_delay` so it reclaims its VIP automatically after recovering (with a grace period to avoid flapping). The backup instance uses `nopreempt` so it never snatches the VIP away from a healthy peer. - **Unicast, not multicast** - `unicast_src_ip` / `unicast_peer` sends VRRP advertisements directly between the two nodes rather than relying on multicast, which can be unreliable on consumer routers/switches with IGMP snooping enabled. --- ## Step 4: Enable and Start Run on **both nodes**: ```bash sudo systemctl enable keepalived.service sudo systemctl start keepalived.service sudo reboot ``` --- ## Step 5: Verify It's Working **Check the service:** ```bash sudo systemctl status keepalived.service ``` **Confirm each node holds its expected VIP:** ```bash ip addr show eth0 ``` Node 1 should show `192.168.0.12/24`; Node 2 should show `192.168.0.13/24`. **Watch keepalived's logs live:** ```bash sudo journalctl -u keepalived -f ``` ### Test an actual failover 1. Power off Node 1: `sudo poweroff` (or `sudo shutdown -h now`, depending on your device type) 2. On Node 2, check its interface again - it should now hold **both** VIPs: ```bash ip addr show eth0 # Should show both 192.168.0.12 and 192.168.0.13 ``` 3. Power Node 1 back on. Because the backup instance uses `nopreempt`, Node 2 keeps serving both VIPs until its own health check fails - there's no disruptive automatic handback. Node 1 simply rejoins as a healthy backup. If both checks pass, you have a working active-active Pi-hole cluster: DNS keeps resolving for your whole network even if one node is powered off, rebooting, or being reimaged. --- ## Wrapping Up With this setup, your router never talks to a single point of failure - it talks to two VIPs that are always being served by a healthy node. The health-check script goes a step further than just "is the process alive," actually confirming DNS resolution end-to-end before considering a node healthy. Combine this with keeping both nodes' Pi-hole configuration in sync (via Teleporter export/import) and you've got a resilient, low-maintenance DNS layer for your home network. Flush! # Markdown Syntax & Shortcodes Guide Source: https://pankaj.xyz/posts/post-syntax-guide/post-syntax-guide.md This post serves as a reference guide to showcase all the various syntax and formatting options available when writing content for this blog. ## 1. Headings Headings are created using the `#` symbol. The `h1` is automatically populated from the title frontmatter, so you should start with `h2` (`##`) for major sections within your post. ### This is an h3 (Sub-heading) Use `###` for sub-sections. #### This is an h4 And `####` for even deeper nesting if absolutely necessary. --- ## 2. Text Formatting You can format your text in a variety of ways to emphasize certain points: - Use **double asterisks** for **bold text**. - Use *single asterisks* or _underscores_ for *italic text*. - You can even combine them for ***bold italics***. - Strikethrough is done using double tildes: ~~this text is crossed out~~. ## 3. Inline Code and Code Blocks When mentioning a variable, command, or file path in the middle of a sentence, use single backticks for `inline-code`. For example: "Be sure to edit your `config.toml` file." For larger snippets, use fenced code blocks. Specify the language for proper syntax highlighting: ### Bash Example ```bash #!/bin/bash echo "Hello, world!" BACKUP_PATHS=("/mnt/storage" "/home/pankaj/stacks") for path in "${BACKUP_PATHS[@]}"; do echo "Backing up $path..." done ``` ### Python Example ```python def fetch_data(url): """Fetches data from the given URL.""" response = requests.get(url) return response.json() ``` ## 4. Links Standard links are created using square brackets for the text and parentheses for the URL: [Visit my GitHub profile](https://github.com/iPankajKumar93) ## 5. Lists ### Unordered Lists You can use `-` or `*` for bulleted lists: * First item * Second item * Nested item A * Nested item B * Third item ### Ordered Lists Use numbers followed by a period: 1. First step 2. Second step 3. Final step ## 6. Blockquotes To quote text from another source or highlight an excerpt, use the `>` symbol: > "Simplicity is the ultimate sophistication." > - Leonardo da Vinci ## 7. Tables Markdown tables are great for structured data: | Service | Port | Description | | :--- | :---: | ---: | | **Gitea** | `3000` | Self-hosted Git service | | **Pi-hole** | `53` | Network-wide ad blocking | | **Grafana** | `3000` | Observability dashboards | ## 8. Images and GIFs There are four main ways to add images depending on your needs. ### Method A: Standard Markdown Image The simplest way to embed an image or a GIF:  ### Method B: Image with Caption (Zola Shortcode) Use the custom `img_caption` shortcode to beautifully display an image with a caption below it: {{