惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Application and Cybersecurity Blog
Application and Cybersecurity Blog
A
About on SuperTechFans
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Help Net Security
Help Net Security
有赞技术团队
有赞技术团队
博客园 - 【当耐特】
O
OpenAI News
美团技术团队
月光博客
月光博客
Apple Machine Learning Research
Apple Machine Learning Research
Schneier on Security
Schneier on Security
Webroot Blog
Webroot Blog
Cyberwarzone
Cyberwarzone
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google Online Security Blog
Google Online Security Blog
T
Tenable Blog
S
Security Affairs
博客园_首页
S
Schneier on Security
Security Latest
Security Latest
T
Threat Research - Cisco Blogs
T
Tailwind CSS Blog
大猫的无限游戏
大猫的无限游戏
Spread Privacy
Spread Privacy
量子位
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
K
Kaspersky official blog
Hugging Face - Blog
Hugging Face - Blog
TaoSecurity Blog
TaoSecurity Blog
博客园 - 聂微东
Vercel News
Vercel News
M
MIT News - Artificial intelligence
T
Troy Hunt's Blog
B
Blog
MongoDB | Blog
MongoDB | Blog
Martin Fowler
Martin Fowler
Attack and Defense Labs
Attack and Defense Labs
L
LINUX DO - 最新话题
D
DataBreaches.Net
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - Franky
W
WeLiveSecurity
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Fortinet All Blogs
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
Check Point Blog
H
Hacker News: Front Page

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Postgres Database, Data Types in Postgres , and The Write Penalty (2026)
Kaushikcoder · 2026-04-26 · via DEV Community

BACKEND ARCHITECTURE MASTERY

Day 8: Databases Part 1 - Postgres, orjson, and The Physics of Writes

15 min read

Series: Logic & Legacy

Day 8 / 30

Level: Intermediate/Senior

📍 Table of Contents (Click to Expand)

 Early in my career, I built an analytics dashboard that tracked user clicks. I stored everything in a massive, flat JSON file on the server. It worked beautifully in local testing. On launch day, two users tried to click a button at the exact same millisecond. The Python script locked the file for User A, crashed for User B, and corrupted the entire JSON structure. We lost a week of data. That day, I learned that a Database is not just a place to store data—it is an operating system designed entirely to survive concurrency.

1. The Storage Divide: Disk vs. RAM

Before we write SQL, you must understand the hardware. Every database architecture decision you make is a brutal negotiation between speed and survival.

An educational infographic detailing database fundamentals, including the difference between RAM and Disk storage, the role of a DBMS as a

  • RAM-Based (In-Memory): Systems like Redis or Memcached store data in the server's volatile memory. Retrieving data takes nanoseconds. It is violently fast. The catch? If the server loses power, or the process restarts, the data is instantly annihilated. We use RAM for caching, session states, and ephemeral queues.
  • Disk-Based (Persistent): Systems like PostgreSQL or MySQL write data to physical SSDs or NVMe drives. This guarantees survival. If the server catches fire, you can pull the drive out, plug it into a new motherboard, and your user's bank balances are still there. The catch? Disk I/O is exponentially slower (microseconds to milliseconds).

2. What Actually is a DBMS?

A Database Management System (DBMS) is not a hard drive. It is a highly complex software engine that sits between your application and the hard drive.

When 10,000 users try to buy the last Taylor Swift concert ticket at the exact same millisecond, the DBMS enforces Concurrency Control. It lines those requests up, locks the specific row in memory, processes the transaction, ensures it is mathematically valid, writes it safely to the physical disk (Durability), and unlocks the row. It prevents race conditions that would otherwise sell the same ticket 10,000 times. It is the ultimate referee of state.

3. Why PostgreSQL Won the Internet

In the 2010s, there was a massive hype cycle around NoSQL databases (like MongoDB) because developers were tired of rigid SQL schemas. Then, PostgreSQL updated its engine to include the JSONB data type. It allowed developers to store unstructured JSON documents inside a relational, strictly-typed SQL database, and query inside that JSON instantly.

Overnight, Postgres cannibalized 80% of the NoSQL use cases. In 2026, Postgres is the undisputed king of backend architecture. It is open-source, massively extensible, and robust enough to run the financial systems of entire countries while maintaining the flexibility of a document store.

4. Postgres Data Types (Stop Using VARCHAR)

Junior developers create tables using auto-incrementing integers for IDs and VARCHAR for everything else. Senior architects use specific types to optimize memory and security:

  • UUID vs Auto-Incrementing IDs: If your user profile URL is /user/142, your competitors know you only have 142 users. They can scrape your entire database by just incrementing the number in a loop. Use UUID (Universally Unique Identifier). It looks like 123e4567-e89b-12d3... and leaks zero information about your scale.
  • TIMESTAMPTZ: Never store a naive date. Always store dates with Time Zone awareness. If a user in Tokyo books a flight to New York, and your server is in London, a naive timestamp will destroy your scheduling logic.
  • JSONB: The binary JSON format. It parses the JSON before storing it, allowing Postgres to index specific keys (like finding all logs where metadata->>'latency' > 2000) at lightning speed.

5. The Physics of Writes and The Write Penalty

Here is the brutal truth of Database Optimization: Every time you write data to a disk, you pay a tax. We call this the Write Penalty.

If you don't have indexes on your tables, finding a specific user requires a Table Scan. The database must physically read every single row on the disk from top to bottom until it finds the match. A Table Scan on 10 million rows will destroy your SQL Performance and take your API offline.

To fix Table Scans, we create a Database Index (specifically a B-Tree Index). Think of it like the index at the back of a textbook. It tells the database exactly what page the data lives on. However, indexes are physically duplicated data structures. If a table has 5 indexes, every single INSERT now requires six separate disk writes (one for the row, five to update the B-Trees). This multiplies your Write Penalty.

"Architecture is the art of trade-offs. 95% of web applications operate on a Read-Heavy Architecture. Users view their feeds, scroll products, and read articles 100 times more often than they post, buy, or write. Therefore, we gladly accept the severe Write Penalty of maintaining indexes, because the alternative—a catastrophic Table Scan during a read operation—is unacceptable."

6. Code: High-Concurrency Relational Logging

To mitigate the Write Penalty at the application layer, we don't open a new database connection for every query. We use Connection Pooling and binary protocols. Python's asyncpg is the fastest driver available because it bypasses string-parsing overhead.

Furthermore, we use orjson (a Rust-backed library) instead of Python's standard json. In high-throughput logging, JSON serialization is often the CPU bottleneck before the database even gets hit. orjson eliminates this.

The Real-World Implementation

Check out the full repository for today's code. We build a high-performance, normalized logging engine mapping services to log\_events via Foreign Keys, and execute powerful relational JOINs over JSONB data.

🐙 View the asyncpg Relational Engine on GitHub →

Analytics Snippet (asyncpg + JSONB)

async def run_complex_analytics(pool):
    # Demonstrates powerful SQL querying: JOINs, Aggregations, and JSONB extraction.
    async with pool.acquire() as conn:
        # Querying INSIDE the metadata JSONB field and casting types
        # We find requests where latency was > 2000ms by joining the services table
        slow_query = """
            SELECT s.service_name, l.created_at, 
                   l.metadata->>'latency_ms' as latency, 
                   l.metadata->>'endpoint' as endpoint
            FROM log_events l
            JOIN services s ON l.service_id = s.service_id
            WHERE (l.metadata->>'latency_ms')::int > 2000
            ORDER BY (l.metadata->>'latency_ms')::int DESC
            LIMIT 5;
        """
        slow_records = await conn.fetch(slow_query)
        for r in slow_records:
            print(f"Service: {r['service_name']} | Latency: {r['latency']}ms")

Enter fullscreen mode Exit fullscreen mode

7. Alternatives: The NoSQL Ecosystem

While Postgres is the default, certain architectural problems require entirely different storage paradigms to escape relational limits.

  • Document Stores (MongoDB): Optimized for rapidly changing schemas and massive horizontal scaling. Instead of tables and rows, you store loose JSON documents.
  • Wide-Column Stores (Cassandra): Built for extreme write-heavy workloads. If you are logging millions of IoT sensor readings per second, Cassandra distributes the Write Penalty across a masterless cluster better than anything else.
  • Graph Databases (Neo4j): Built to query relationships. If you need to find "Friends of Friends who also bought Product X", a relational database will choke on massive JOIN operations. A Graph database traverses those nodes instantly.

🔥 DAY 9 TEASER: THE B-TREE ALGORITHM (DATABASES PART 2)

We established that Table Scans are fatal, and Indexes fix them. But what exactly is an index under the hood? Tomorrow, we rip open the database engine to explore Index Cardinality, Clustered vs Composite Indexes, Postgres EXPLAIN ANALYZE, and the legendary B+ Tree data structure that powers the internet's search capabilities.

📚 Deep Diver Resources

If you want to master relational limits and NoSQL architectures, these are mandatory reading:

Frequently Asked Questions

Q: If memory is so fast, why don't we build entire databases in RAM?

A: We do! In-memory databases like Redis and Memcached are exactly this. However, RAM is incredibly expensive compared to SSD storage. Storing a 5TB relational dataset entirely in RAM would bankrupt a startup, and managing the persistence (saving snapshots to disk to prevent data loss on crash) becomes a massive engineering bottleneck.

Q: Why did you use orjson instead of the built-in Python json library?

A: Python's native json library is written in pure Python/C and is relatively slow. orjson is written in Rust. When you are processing millions of log entries or API payloads, CPU serialization becomes a massive bottleneck. orjson can serialize dictionaries to byte-strings magnitudes faster, freeing up the CPU to handle more concurrent requests.

Q: Should I use MongoDB for a new project because it's schema-less?

A: "Schema-less" is a dangerous myth. If your database doesn't enforce the schema, your application code must enforce it (checking if fields exist before accessing them, causing massive code bloat). For 90% of projects, Postgres with a well-designed relational schema—using JSONB columns for the truly dynamic parts like metadata—is much safer and more performant long-term.

Architectural Consulting

If you are building a data-intensive AI application and require a Senior Engineer to architect your secure, high-concurrency backend, I am available for direct contracting.

Explore Enterprise Engagements →

[← Previous

Day 7: Identity Federation](/day-7-sso-oidc)
[Next →

Day 9: Database Indexing](/day-9-btree-indexes)


Originally published at https://logicandlegacy.blogspot.com