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

推荐订阅源

S
Schneier on Security
P
Proofpoint News Feed
Apple Machine Learning Research
Apple Machine Learning Research
WordPress大学
WordPress大学
博客园 - Franky
V
V2EX
爱范儿
爱范儿
J
Java Code Geeks
小众软件
小众软件
Last Week in AI
Last Week in AI
The Cloudflare Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hugging Face - Blog
Hugging Face - Blog
T
The Blog of Author Tim Ferriss
酷 壳 – CoolShell
酷 壳 – CoolShell
The Register - Security
The Register - Security
GbyAI
GbyAI
Vercel News
Vercel News
Y
Y Combinator Blog
腾讯CDC
F
Fortinet All Blogs
I
InfoQ
N
Netflix TechBlog - Medium
B
Blog RSS Feed
D
Docker
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
量子位
博客园 - 司徒正美
阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
H
Help Net Security
云风的 BLOG
云风的 BLOG
A
About on SuperTechFans
Scott Helme
Scott Helme
T
Tor Project blog
U
Unit 42
Google Online Security Blog
Google Online Security Blog
PCI Perspectives
PCI Perspectives
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
NISL@THU
NISL@THU
D
Darknet – Hacking Tools, Hacker News & Cyber Security
aimingoo的专栏
aimingoo的专栏
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
Security Archives - TechRepublic
Security Archives - TechRepublic

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
Spatial Search Performance: How I Got 100x Faster Queries With PostGIS and Redis GEO
KevinTen · 2026-06-25 · via DEV Community

Spatial Search Performance: How I Got 100x Faster Queries With PostGIS and Redis GEO

Honestly, I thought building a spatial search would be easy. "It's 2026, databases have spatial indexes built in — how hard can it be?" I said to myself after three energy drinks at 2 AM. Three weeks later, I had a production system where a simple "find points within 1km" query took 8 seconds.

Eight seconds. On a dataset of only 10,000 points.

So here's the thing — I learned the hard way that "having spatial indexes" isn't the same as having fast spatial queries. If you're building anything with location-based search, stick around — this is everything I wish someone had told me before I started.

The Problem: "Find all spots within 1km of me"

Spatial Memory lets users pin photos and notes to physical coordinates. When you open the app, it needs to show everything interesting within walking distance. The query sounds simple:

Give me all points within 1 kilometer of (latitude, longitude)
Sort them by distance
Return the closest 20 results

That's it. That's all I wanted. My first implementation? Straightforward with PostGIS:

SELECT id, lat, lng, name, 
       ST_Distance(geom, ST_SetSRID(ST_MakePoint($1, $2), 4326)) AS distance
FROM points
WHERE ST_DWithin(geom, ST_SetSRID(ST_MakePoint($1, $2), 4326), 1000)
ORDER BY distance
LIMIT 20;

Looks right, right? I created a GIST index on the geom column, added the query, called it a day.

Then I tested it.

Query time: 7.8 seconds.

I checked the index — yes, it was there. I checked the statistics — everything looked fine. 10,000 rows shouldn't take 8 seconds. What gives?

The First Surprise: SRID and Projection Matters

Here's mistake number one: I was using 4326 (WGS84) which is great for storing coordinates, but ST_DWithin with distances in meters gets complicated because 4326 uses degrees, not meters.

PostGIS does have geography type that handles meters correctly, but guess what? The query planner doesn't always use GIST indexes efficiently with geography when you have larger datasets. Or maybe I was doing it wrong — honestly, after three days of debugging, I stopped caring why and just looked for a better way.

The fix that cut my query time from 8 seconds to 800ms? Transform to a projected coordinate system that uses meters:

-- Before (slow): SRID 4326, degrees
ST_DWithin(geom, ST_SetSRID(ST_MakePoint($1, $2), 4326), 0.009) -- degrees ≈ 1km

-- After (faster): Transform to Web Mercator (meters)
ST_DWithin(
  geom_mercator,
  ST_Transform(ST_SetSRID(ST_MakePoint($1, $2), 4326), 3857),
  1000 -- actual meters, no guessing
)

I added a second column geom_mercator that's already transformed, created a new GIST index on it, and boom — 10x faster immediately.

// In Go with GORM
type Point struct {
    ID           uint      `json:"id"`
    Lat          float64   `json:"lat"`
    Lng          float64   `json:"lng"`
    Geom         geog.GeoJSON `gorm:"column:geom;srid:4326"`
    GeomMercator geometry.Polygon `gorm:"column:geom_mercator;srid:3857"`
}

// Auto-update geom_mercator when lat/lng changes
func (p *Point) BeforeSave(*gorm.DB) error {
    // Transform from 4326 to 3857 for fast queries
    p.GeomMercator = geometry.NewPoint(geometry.Coordinate{X: p.Lng, Y: p.Lat}, 3857)
    return nil
}

Lesson #1: Store your data in 4326 (everyone expects WGS84), but query in a projected CRS that uses actual meters. Your query planner will thank you.

The Second Surprise: Cache Hot Zones with Redis GEO

Even with 800ms, that's still too slow for mobile. Users open the app, they expect results instantly. 800ms feels laggy.

But think about it — most spatial queries hit the same popular areas over and over. Tourist attractions, city centers, university campuses. Why go to PostGIS every time when the results don't change that often?

Enter Redis GEO.

I added a simple two-level caching strategy:

  1. Redis GEO stores all point coordinates (it's just a sorted set under the hood anyway)
  2. For any query, first get candidate point IDs from Redis with GEORADIUS
  3. Go to Postgres only for those candidates to get the actual data
  4. Cache the full JSON result for popular queries for 5 minutes

Here's what that looks like in code:

import (
    "context"
    "strconv"
    "github.com/go-redis/redis/v8"
)

func (s *SpatialService) SearchNearby(ctx context.Context, lat, lng float64, radiusKm float64, limit int) ([]*Point, error) {
    radiusMeters := radiusKm * 1000

    // Step 1: Get candidate IDs from Redis GEO first
    // This is almost always <1ms
    ids, err := s.redis.GeoRadius(ctx, "spatial:points", lng, lat, &redis.GeoRadiusQuery{
        Radius:      radiusMeters,
        Unit:        "m",
        WithCoord:   false,
        WithDist:    false,
        WithGeoHash: false,
        Count:       limit * 2, // Get extra for sorting
        Sort:        "ASC",
    }).Result()

    if err != nil {
        // Fallback to full PostGIS query if Redis down
        return s.fullPostGISSearch(lat, lng, radiusKm, limit)
    }

    // Convert results to numeric IDs
    pointIDs := make([]uint, len(ids))
    for i, res := range ids {
        id, _ := strconv.ParseUint(res.Name, 10, 32)
        pointIDs[i] = uint(id)
    }

    // Step 2: Only query the specific IDs we need from Postgres
    // Instead of scanning the whole table, this is just a few index lookups
    var points []*Point
    err = s.db.Where("id IN ?", pointIDs).Find(&points).Error

    // Sort by distance (Redis already did this, but just to be safe)
    // ... sorting code ...

    return points, nil
}

// When inserting a new point, add it to Redis too
func (s *SpatialService) InsertPoint(ctx context.Context, p *Point) error {
    err := s.db.Create(p).Error
    if err != nil {
        return err
    }
    // Add to Redis GEO
    _, err = s.redis.GeoAdd(ctx, "spatial:points", &redis.GeoLocation{
        Longitude: p.Lng,
        Latitude:  p.Lat,
        Name:      strconv.FormatUint(uint64(p.ID), 10),
    }).Result()
    return err
}

The result? Average query time dropped from 800ms to 30ms. That's another 27x improvement. Combined with the first fix, that's ~260x faster than my original query.

Wait — but what about memory? Redis is in-memory after all. Let's do the math:

  • Each point in Redis GEO is a sorted set entry
  • Each entry is ~ 32 bytes (name is 4-8 bytes + score 8 bytes + pointers)
  • 100,000 points ≈ 3.2 MB
  • 1,000,000 points ≈ 32 MB

That's nothing. Even on the cheapest VPS, this fits in memory easily.

Lesson #2: PostGIS is powerful, but for simple radius searches, Redis GEO gives you almost instant results for almost no memory cost. Use it as a filter before hitting the database.

The Third Surprise: Index Selectivity Matters

Wait a minute — why was the original query so slow even with a GIST index?

I dug into the query plan with EXPLAIN ANALYZE and found it:

Seq Scan on points  ...  (cost=0.00..1234.56 rows=10 width=... actual time=7000.00..7800.00)

It was doing a sequential scan! Not using the index at all. Why? Because with the wrong SRID and distance units, the query planner thought the search would hit most of the table, so a sequential scan was cheaper than random I/O.

Even after fixing the SRID, if you're searching a large area (like 10km radius in a dense city), the query planner might still choose a sequential scan because it expects many rows. That's still slower than it needs to be.

What fixed this? Two things:

  1. Cluster your data using the spatial index: CLUSTER points USING idx_points_geom_mercator; This physically orders points that are near each other on disk. Fewer random reads = faster queries.

  2. Set reasonable limits and analyze regularly: VACUUM ANALYZE points; Postgres query planning depends on good statistics. After you add a bunch of points, update those stats.

  3. If you always limit to 20 results, tell Postgres that: LIMIT 20 helps the query planner choose an index scan because it can stop searching once it has enough results.

After clustering, I got another 2-3x speedup on cold cache queries. Not bad for a one-liner.

Lesson #3: Always check EXPLAIN ANALYZE. The index exists doesn't mean it's being used.

Pros and Cons: What Works, What Doesn't

Honestly, I've been running this setup in production for three months now. Let me be straight with you — this isn't the "latest and greatest" with some fancy new spatial database. It's PostGIS + Redis, two tools you probably already know. Does it actually work?

What's Good ✅

  • Simplicity: You don't need to operate another specialized database. If you already have Postgres and Redis, you're done. No extra infrastructure to manage.
  • Performance: 100x faster than my naive approach. 20-50ms for most queries, even with tens of thousands of points. That's fast enough for mobile.
  • Memory efficiency: Redis only stores coordinates and IDs, not the whole point data. Even 100k points is <50MB.
  • Scales well: Add more points, the Redis lookup is still O(log N). The Postgres lookup is just primary key lookups — super fast.
  • Resilience: If Redis goes down, you fall back to the full PostGIS query. It's slower but still works. No outage.

What's Bad ❌

  • Extra work: You have to keep Redis in sync with your Postgres data. If you delete/update points, you need to delete them from Redis too. Extra code, extra moving parts.
  • Approximate distance ordering: Redis GEO uses sorted set scores with 52 bits of precision. That's accurate enough for most applications, but if you need sub-meter precision, this isn't for you. For a social app like mine, it's totally fine.
  • No fancy spatial operations: This works great for radius searches. If you need polygon intersections, complex joins, or projections, you still need PostGIS. This is a optimization for the common case, not a replacement.
  • Clustering needs maintenance: CLUSTER rewrites the whole table, it locks it. You can't do it live on a busy production table. You need to schedule it during maintenance windows. For my side project, that's fine. For a busy app, you need to plan accordingly.

What I Would Do Differently Next Time

If I were starting over today, knowing what I know now, I'd still choose PostGIS + Redis GEO. But I'd do a few things differently:

  1. Start with the simplest thing that works: I overcomplicated it with fancy PostGIS features at the beginning. I should have started with Redis GEO + Postgres primary key lookups and added complexity only when I needed it.

  2. Use smaller radii by default: Most users aren't searching for everything within 10km. They want nearby spots. 1km default gives you fewer candidates, faster queries, and more relevant results anyway.

  3. Don't worry about precision: For consumer apps, 1-2 meters error doesn't matter. Users are on foot, they can't tell the difference anyway. Redis GEO is more than accurate enough.

  4. Backup your Redis GEO: If your Redis data gets wiped, you can rebuild it from Postgres. Just iterate through all points and re-add them. Write that script early. I learned this the hard way when I accidentally flushed my Redis cache while debugging.

The Big Picture

Building Spatial Memory has taught me that most of the time, you don't need fancy new technology. You just need to combine two mature tools the right way.

PostGIS is amazing for complex spatial work. But for the common case — "find everything within X km of me" — you don't need all that power. Let Redis do what it's good at (fast in-memory lookups), let Postgres do what it's good at (storing your data and handling complex queries when you need them).

I went from 8 seconds to 20ms with two simple changes. That's the power of knowing your tools, not just using the newest tool.

Wrapping Up

So that's my story. Eight seconds to 20ms, three weeks of debugging, a lot of coffee, and a lot of lessons learned.

If you're building something with location search:

  • Store in 4326, query in projected meters
  • Use Redis GEO as a first-level filter
  • Check EXPLAIN ANALYZE — your index might not be used
  • Cluster for better locality if you can

It's not rocket science, but it's the kind of thing no tutorial really tells you. They just show you the working query and call it done. They don't tell you about the 8 seconds.

What about you — have you built anything with spatial search? What's your setup? Did you go all-in on PostGIS, or use Elasticsearch, or something else entirely? I'd love to hear about what's worked for you in the comments below.

The code for this project is open source on GitHub if you want to dig in.