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

推荐订阅源

D
DataBreaches.Net
量子位
博客园 - 三生石上(FineUI控件)
Hacker News - Newest:
Hacker News - Newest: "LLM"
月光博客
月光博客
博客园 - 叶小钗
爱范儿
爱范儿
S
SegmentFault 最新的问题
V2EX - 技术
V2EX - 技术
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Security Archives - TechRepublic
Security Archives - TechRepublic
小众软件
小众软件
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security @ Cisco Blogs
V
Visual Studio Blog
V
V2EX
Schneier on Security
Schneier on Security
Cloudbric
Cloudbric
有赞技术团队
有赞技术团队
C
Check Point Blog
T
Troy Hunt's Blog
Google DeepMind News
Google DeepMind News
Google DeepMind News
Google DeepMind News
TaoSecurity Blog
TaoSecurity Blog
Engineering at Meta
Engineering at Meta
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
Schneier on Security
N
Netflix TechBlog - Medium
Project Zero
Project Zero
Last Week in AI
Last Week in AI
N
News and Events Feed by Topic
Microsoft Azure Blog
Microsoft Azure Blog
NISL@THU
NISL@THU
T
The Exploit Database - CXSecurity.com
AWS News Blog
AWS News Blog
博客园 - 聂微东
S
Securelist
腾讯CDC
O
OpenAI News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
A
About on SuperTechFans
Microsoft Security Blog
Microsoft Security Blog
B
Blog
博客园 - 【当耐特】
Y
Y Combinator Blog
N
News and Events Feed by Topic
Recorded Future
Recorded Future
Vercel News
Vercel News
PCI Perspectives
PCI Perspectives
Security Latest
Security Latest

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
When zippopotam.us 404s on a real US ZIP: building a 4-tier geocoding fallback
GasPriceChec · 2026-05-14 · via DEV Community

ZIP-to-lat/lng feels like a solved problem. There are something like 41,000 active US ZIP codes. They're a public dataset. They're geocoded. Multiple free APIs serve them. You wire one up, it works, you ship.

That's what I thought. Then a user reported that the gas station on his block was showing as "8,247 miles away."

Quick context: I run a gas price finder side project. When you enter a ZIP, the site looks up that ZIP's lat/lng, then sorts nearby gas stations by driving distance. If the ZIP's lat/lng resolves to (0, 0), the Haversine math returns absurd distances because (0, 0) is in the middle of the Atlantic Ocean off the coast of Africa.

The user's ZIP was 75072. McKinney, Texas. Population 200,000. Not some obscure rural P.O. box. A real ZIP code with a real population center.

My geocoder was returning (0, 0).

What was actually happening

My geocoder, at the time, was a single fetch:

async function zipToLatLng(zip: string) {
  const res = await fetch(`https://api.zippopotam.us/us/${zip}`);
  if (!res.ok) return { lat: 0, lng: 0 };
  const data = await res.json();
  return {
    lat: parseFloat(data.places[0].latitude),
    lng: parseFloat(data.places[0].longitude),
  };
}

Enter fullscreen mode Exit fullscreen mode

zippopotam.us is free, fast, and was working for everything I'd tested. So when 75072 returned a 404, my fallback was the (0, 0) sentinel. Garbage in, garbage out.

I dug a little. Curled the API directly:

$ curl -i https://api.zippopotam.us/us/75072
HTTP/1.1 404 Not Found

Enter fullscreen mode Exit fullscreen mode

Then I tried 75070, the neighboring ZIP:

$ curl -i https://api.zippopotam.us/us/75070
HTTP/1.1 200 OK

Enter fullscreen mode Exit fullscreen mode

So 75070 is in zippopotam's data, 75072 isn't. Two ZIPs in the same city, one block apart, one of them missing. There's no announced data freshness commitment from zippopotam (it's a free service maintained by one person), so this isn't a bug to report. It's just a gap.

I spot-checked. Out of a sample of 100 ZIPs from my user logs, zippopotam returned 404 on 4 of them. A 4% gap rate. On a programmatic site with 33,620 pages, that's about 1,300 pages where the geocoder silently returned (0, 0) and broke distance math.

This is the moment when "I'll just use a free API" stops scaling.

The chain I shipped

What I needed wasn't a better single source. It was a chain of sources, each with different tradeoffs, ordered from cheapest to most expensive:

  1. Static file lookup (instant, zero network)
  2. Redis cache (instant, one network hop)
  3. zippopotam.us (~150ms, free, has gaps)
  4. Nominatim (~400ms, free, rate-limited, covers gaps)
  5. Sentinel (0, 0) with degraded behavior

Here's the actual implementation, slightly cleaned up:

import { Redis } from '@upstash/redis';
import zipContent from './zipContent.json';

const redis = Redis.fromEnv();

type LatLng = { lat: number; lng: number };

export async function zipToLatLng(zip: string): Promise<LatLng> {
  // Tier 1: static file (33,620 pre-resolved ZIPs)
  const staticEntry = (zipContent as Record<string, any>)[zip];
  if (staticEntry?.lat && staticEntry?.lng) {
    return { lat: staticEntry.lat, lng: staticEntry.lng };
  }

  // Tier 2: Redis cache (for ZIPs we've resolved at runtime)
  const cached = await redis.get<LatLng>(`zip:${zip}`);
  if (cached) return cached;

  // Tier 3: zippopotam.us
  try {
    const res = await fetch(`https://api.zippopotam.us/us/${zip}`, {
      signal: AbortSignal.timeout(2000),
    });
    if (res.ok) {
      const data = await res.json();
      const result = {
        lat: parseFloat(data.places[0].latitude),
        lng: parseFloat(data.places[0].longitude),
      };
      await redis.set(`zip:${zip}`, result, { ex: 60 * 60 * 24 * 30 });
      return result;
    }
  } catch (e) {
    // network error or timeout, fall through
  }

  // Tier 4: Nominatim
  try {
    const res = await fetch(
      `https://nominatim.openstreetmap.org/search?postalcode=${zip}&country=us&format=json&limit=1`,
      {
        headers: { 'User-Agent': 'GasPriceCheck/1.0 (contact@example.com)' },
        signal: AbortSignal.timeout(3000),
      }
    );
    if (res.ok) {
      const data = await res.json();
      if (data.length > 0) {
        const result = {
          lat: parseFloat(data[0].lat),
          lng: parseFloat(data[0].lon),
        };
        await redis.set(`zip:${zip}`, result, { ex: 60 * 60 * 24 * 30 });
        return result;
      }
    }
  } catch (e) {
    // network error or timeout, fall through
  }

  // Tier 5: sentinel
  return { lat: 0, lng: 0 };
}

Enter fullscreen mode Exit fullscreen mode

Five tiers, ordered by cost. Each one only runs if the previous one didn't find an answer. The static file handles 99% of requests in zero time. Redis handles the runtime-resolved ones. The two API tiers are the actual fallbacks.

A few notes on the implementation choices.

Tier 1: pre-resolving everything you can ahead of time

The biggest performance win wasn't the chain. It was Tier 1: a static JSON file with every ZIP I knew about, pre-resolved to lat/lng once at build time.

I wrote a Python script (enrich-zip-latlng.py) that walks my full ZIP list, calls zippopotam for each one, falls back to Nominatim for the gaps, and writes the results to zipContent.json. The script is resumable: it checkpoints to a JSON file every 100 ZIPs, so if it crashes (and it did, several times, on intermittent rate limits), you restart and it picks up where it left off.

import json, time
from pathlib import Path
import requests

CHECKPOINT = Path("zip_latlng_progress.json")
OUTPUT = Path("zipContent.json")

def load_progress():
    if CHECKPOINT.exists():
        return json.loads(CHECKPOINT.read_text())
    return {"resolved": {}, "remaining": load_zip_list()}

def resolve(zip_code):
    # try zippopotam, fall back to Nominatim
    try:
        r = requests.get(f"https://api.zippopotam.us/us/{zip_code}", timeout=5)
        if r.ok:
            d = r.json()
            return float(d["places"][0]["latitude"]), float(d["places"][0]["longitude"])
    except Exception:
        pass
    try:
        r = requests.get(
            "https://nominatim.openstreetmap.org/search",
            params={"postalcode": zip_code, "country": "us", "format": "json", "limit": 1},
            headers={"User-Agent": "ZipEnricher/1.0"},
            timeout=10,
        )
        if r.ok:
            data = r.json()
            if data:
                return float(data[0]["lat"]), float(data[0]["lon"])
    except Exception:
        pass
    return None, None

Enter fullscreen mode Exit fullscreen mode

After running this against all 33,620 ZIPs (took about 9 hours of wall clock time, mostly idle waiting for rate limits), I had 100% coverage. Every known ZIP resolves in zero network calls at runtime.

The runtime fallback chain is now a safety net for the ZIPs that aren't in zipContent.json (mostly newly-issued ZIPs and edge-case P.O. box codes). It's load-bearing maybe 0.1% of the time. The other 99.9% of requests hit Tier 1 and exit.

Tier 4: Nominatim's etiquette is real

Nominatim is OpenStreetMap's geocoder. It's free. It's also explicit about its rate limits: 1 request per second, max. They publish a usage policy. They will rate-limit you (or ban your IP) if you violate it.

Two things matter for keeping Nominatim happy:

  1. Set a real User-Agent header. They block requests with the default node-fetch/1.0 UA. Use something like MyApp/1.0 (contact@example.com).
  2. Throttle. If you're calling Nominatim from a script, sleep at least 1 second between calls. From an API route serving real users, this is fine because user traffic is naturally sparse.

If you're going to depend on Nominatim at scale, you should run your own instance. It's open source and Dockerized. For a side project hitting it 1-2 times a day, the public instance is fine.

Tier 5: the sentinel and graceful degradation

When all four tiers fail, my function returns { lat: 0, lng: 0 }. The downstream code needs to handle this without producing garbage.

In my case, the downstream consumer is a "nearest gas stations" sorter that uses Haversine distance. If the user's coords are (0, 0), Haversine returns absurd distances for every station. So I added a guard:

const userCoords = await zipToLatLng(zip);
if (userCoords.lat === 0 && userCoords.lng === 0) {
  return stations; // unsorted, no distance column
}
return sortByDistance(stations, userCoords);

Enter fullscreen mode Exit fullscreen mode

If we can't geocode, we still show stations. We just don't sort by distance, and we don't display the distance column. The page degrades gracefully instead of showing "8,247 miles away" everywhere.

This is the "fail open" pattern: when the dependency fails, the user still gets a useful page, just with less information. Better than failing the whole request.

What I'd tell my past self

Three things.

One. "Free APIs have gaps" is not a hypothesis, it's a default assumption. Any API where the provider is one person, a small org, or a "we'll keep this up as a community resource" project will have data quality issues somewhere. Plan for it from day one.

Two. Pre-resolve the long tail at build time, not request time. Runtime API calls are a tax on every user. If you have a finite, enumerable input space (like US ZIP codes), resolve the whole space once and cache the results to disk. This collapses the runtime cost from "1 API call per request" to "1 file lookup per request."

Three. Build the chain before you need it. The temptation when the first source works is to ship the single-source version and add fallbacks "later." Later means after a user reports a bug. Building the chain up front takes maybe 2 hours and saves you the embarrassment of "8,247 miles away" emails.

The architecture lesson here generalizes beyond ZIPs. Anywhere you have a dependency that maps "A → B" deterministically and the input space is finite, the move is the same: pre-resolve at build, cache at runtime, fall back to alternative providers, degrade gracefully when all else fails. ZIP geocoding, currency conversion, language code lookups, country data, time zone data, postal codes for any country with public data: same pattern.

The whole rebuild took about a weekend. I'd do it again in an afternoon now that I know the shape. The hard part wasn't the code, it was admitting that "free API + sentinel" wasn't actually a fallback strategy. It was a single-source-of-truth dressed up as one.

If you've shipped a layered geocoding chain on top of zippopotam, Nominatim, or a paid alternative, drop your tier ordering in the comments. Curious what other chains people are running.