How to Build a Geocoder Inside Postgres with Web APIs | PostgreSQL & PostGIS
How to Build a Geocoder Inside Postgres with Web APIs
Geocoding is the process of converting a human-readable location such as an address, city, postal code, or landmark into geographic coordinates typically latitude and longitude. Reverse geocoding performs the opposite operation: it takes coordinates and determines the corresponding address or location.
For modern applications, geocoding is commonly handled by external services such as Google Maps, Mapbox, HERE, or OpenStreetMap-based APIs. However, there are situations where keeping geospatial processing closer to your database is valuable.
With PostgreSQL + PostGIS + Web APIs, you can build a powerful geocoding workflow where PostgreSQL stores geographic data, PostGIS performs spatial operations, and a web API supplies or consumes geocoding information.
This approach is particularly useful for applications involving delivery systems, logistics, customer locations, real-estate platforms, geographic analytics, service areas, and location-based search.
What Is Geocoding?
Geocoding converts a textual location into geographic coordinates.
For example:
Input:
Pune, Maharashtra, India
Output:
Latitude: 18.5204
Longitude: 73.8567
These coordinates can then be stored in PostgreSQL and used for spatial queries.
A simplified workflow looks like this:
User Address
|
v
Web API
|
v
Geocoding Service
|
v
Latitude + Longitude
|
v
PostgreSQL + PostGIS
|
v
Spatial Queries / Analytics
The database does not necessarily need to perform every part of the geocoding process itself. Instead, PostgreSQL can act as the central geographic data store and spatial processing engine.
Why Use PostgreSQL for Geocoding?
PostgreSQL becomes particularly powerful when combined with the PostGIS extension.
PostGIS adds support for:
- Points
- Lines
- Polygons
- Geographic coordinates
- Spatial indexes
- Distance calculations
- Spatial intersections
- Containment queries
- Nearest-neighbor searches
- Geographic transformations
For example, once customer locations are stored as PostGIS points, you can ask:
SELECT *
FROM customers
WHERE ST_DWithin(
location,
ST_SetSRID(ST_MakePoint(73.8567, 18.5204), 4326)::geography,
5000
);
This query can identify customers within approximately 5 kilometers of a particular location.
PostgreSQL and PostGIS Architecture
A typical geocoding architecture can be designed like this:
Web Application
|
v
REST API Layer
|
+------------+------------+
| |
v v
Geocoding API PostgreSQL
| + PostGIS
| |
v v
Latitude / Longitude Spatial Database
| |
+------------+------------+
|
v
Location Analytics
The web API can handle requests from applications while PostgreSQL stores normalized addresses and geographic coordinates.
Step 1: Install PostGIS
First, PostgreSQL needs the PostGIS extension.
Inside the target database:
CREATE EXTENSION postgis;
Verify the installation:
SELECT PostGIS_Full_Version();
You should receive information about the installed PostGIS version.
PostGIS provides spatial data types and functions that PostgreSQL itself does not provide by default.
Step 2: Create an Address Table
Let’s create a table for storing addresses.
CREATE TABLE addresses (
id BIGSERIAL PRIMARY KEY,
address_text TEXT NOT NULL,
city TEXT,
state TEXT,
country TEXT,
postal_code VARCHAR(20),
latitude DOUBLE PRECISION,
longitude DOUBLE PRECISION,
location GEOGRAPHY(POINT, 4326),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Here, the location column stores the geographic point.
The SRID 4326 represents WGS 84, the coordinate reference system commonly used for GPS coordinates.
Step 3: Store Latitude and Longitude
Suppose an API returns:
Latitude: 18.5204
Longitude: 73.8567
We can create a PostGIS point:
ST_SetSRID(
ST_MakePoint(73.8567, 18.5204),
4326
)
Notice the order:
longitude, latitude
not:
latitude, longitude
This is an important detail when working with PostGIS.
We can insert the location like this:
INSERT INTO addresses (
address_text,
city,
state,
country,
postal_code,
latitude,
longitude,
location
)
VALUES (
'Pune, Maharashtra, India',
'Pune',
'Maharashtra',
'India',
'411001',
18.5204,
73.8567,
ST_SetSRID(
ST_MakePoint(73.8567, 18.5204),
4326
)
);
Step 4: Understand the Role of a Web Geocoding API
PostgreSQL alone does not magically know the coordinates of every address.
A geocoding service can accept:
Pune, Maharashtra, India
and return structured geographic information such as:
{
"latitude": 18.5204,
"longitude": 73.8567,
"city": "Pune",
"state": "Maharashtra",
"country": "India"
}
The application can then store that information in PostgreSQL.
The overall process becomes:
Address
|
v
Geocoding API
|
v
JSON Response
|
v
Application/API Server
|
v
PostgreSQL
|
v
PostGIS Location
Step 5: Build a Simple Geocoding API
A backend application can expose an endpoint such as:
POST /geocode
The request might contain:
{
"address": "Pune, Maharashtra, India"
}
The application sends this address to a geocoding provider.
After receiving the coordinates, it stores them in PostgreSQL.
The API can then return:
{
"address": "Pune, Maharashtra, India",
"latitude": 18.5204,
"longitude": 73.8567
}
This gives your application a reusable geocoding layer.
Step 6: Avoid Geocoding the Same Address Repeatedly
One of the biggest improvements you can make is caching geocoding results.
Suppose 10,000 users enter:
Pune, Maharashtra, India
There is little value in sending the same address to an external API thousands of times.
Instead, store the result:
Address
|
v
Check PostgreSQL
|
+---- Found ----> Return stored coordinates
|
+---- Not Found -> Call Geocoding API
|
v
Store result
|
v
Return result
This reduces:
- API usage
- Network requests
- Response latency
- External service dependency
- Operating costs
Step 7: Normalize Addresses
Caching becomes much more effective when addresses are normalized.
For example:
Pune Maharashtra India
Pune, Maharashtra, India
PUNE, MAHARASHTRA, INDIA
could represent the same location.
You can create a normalized address field:
ALTER TABLE addresses
ADD COLUMN normalized_address TEXT;
Then application logic can convert input into a consistent format before searching.
For example:
Input:
PUNE, Maharashtra, India
Normalized:
pune, maharashtra, india
A unique index can then help prevent duplicate geocoding requests.
CREATE UNIQUE INDEX idx_normalized_address
ON addresses(normalized_address);
Step 8: Add a Spatial Index
For large datasets, a spatial index is extremely important.
Create a GiST index:
CREATE INDEX idx_addresses_location
ON addresses
USING GIST(location);
This allows PostgreSQL/PostGIS to efficiently execute many spatial queries.
Without an appropriate spatial index, a query may need to examine a large portion of the table.
With millions of locations, this difference can be significant.
Step 9: Find Locations Near a User
Suppose a user is located at:
Latitude: 18.5204
Longitude: 73.8567
You can search for nearby addresses using:
SELECT
id,
address_text,
ST_Distance(
location,
ST_SetSRID(
ST_MakePoint(73.8567, 18.5204),
4326
)::geography
) AS distance_meters
FROM addresses
ORDER BY location <-> ST_SetSRID(
ST_MakePoint(73.8567, 18.5204),
4326
)
LIMIT 10;
This is useful for applications such as:
- Nearby stores
- Delivery locations
- Service centers
- Hospitals
- Restaurants
- Drivers
- Warehouses
Step 10: Use ST_DWithin for Radius Searches
If the requirement is simply:
Find all locations within 5 km.
You can use:
SELECT id, address_text
FROM addresses
WHERE ST_DWithin(
location,
ST_SetSRID(
ST_MakePoint(73.8567, 18.5204),
4326
)::geography,
5000
);
The final value:
5000
represents meters.
Therefore:
5000 = 5 km
10000 = 10 km
25000 = 25 km
Step 11: Reverse Geocoding
Geocoding converts:
Address → Coordinates
Reverse geocoding performs:
Coordinates → Address
For example:
18.5204, 73.8567
could be sent to a reverse-geocoding API.
The API might return:
{
"city": "Pune",
"state": "Maharashtra",
"country": "India"
}
Your application can then store this information.
This is useful for:
- GPS tracking
- Delivery applications
- Fleet management
- User location detection
- Location history
- Field-service applications
Step 12: Build a Reverse-Geocoding Endpoint
Your application could expose:
GET /reverse-geocode?lat=18.5204&lon=73.8567
The backend performs the following:
Latitude + Longitude
|
v
Reverse Geocoding API
|
v
Address Information
|
v
PostgreSQL
|
v
API Response
The response could look like:
{
"latitude": 18.5204,
"longitude": 73.8567,
"city": "Pune",
"state": "Maharashtra",
"country": "India"
}
Step 13: Store Raw API Responses
For production systems, it can sometimes be useful to retain the original API response.
For example:
CREATE TABLE geocoding_requests (
id BIGSERIAL PRIMARY KEY,
query_text TEXT,
response JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
The JSONB data type allows PostgreSQL to store structured JSON efficiently.
You could store:
{
"query": "Pune, Maharashtra",
"latitude": 18.5204,
"longitude": 73.8567,
"provider": "example"
}
This can help with:
- Debugging
- Auditing
- Reprocessing
- Provider comparison
- Troubleshooting incorrect results
Step 14: Handle API Failures
External APIs can fail.
Possible failures include:
Timeout
Rate limit exceeded
Invalid API key
Network failure
Invalid address
Provider outage
Incomplete response
Your application should therefore implement error handling.
A good workflow is:
Request
|
v
Check Local Cache
|
+---- Found → Return Result
|
v
Call API
|
+---- Success → Store + Return
|
+---- Failure → Retry / Queue / Error Response
Avoid blindly retrying requests because repeated retries can make rate-limit problems worse.
Step 15: Implement Retry Logic
A production system can use controlled retries.
For example:
Attempt 1
|
v
Failure
|
v
Wait
|
v
Attempt 2
|
v
Failure
|
v
Attempt 3
|
v
Permanent failure / queue for later
Exponential backoff is often preferable to immediately repeating the request.
Step 16: Use Asynchronous Geocoding for Large Datasets
Suppose you need to geocode 5 million customer addresses.
Doing this synchronously during a database transaction is a bad design.
Instead:
Customer Import
|
v
PostgreSQL
|
v
Geocoding Queue
|
v
Worker Processes
|
v
External Geocoding API
|
v
PostgreSQL
This allows the import process to continue while background workers process addresses.
A queue-based architecture can also control API request rates.
Step 17: Track Geocoding Status
Add a status column:
ALTER TABLE addresses
ADD COLUMN geocoding_status VARCHAR(20)
DEFAULT 'PENDING';
Possible values:
PENDING
PROCESSING
SUCCESS
FAILED
You can also store:
ALTER TABLE addresses
ADD COLUMN geocoding_attempts INTEGER DEFAULT 0;
and:
ALTER TABLE addresses
ADD COLUMN geocoded_at TIMESTAMP;
Now the system can identify which addresses still need processing.
Step 18: Build a Geocoding Queue
A simple queue table might look like:
CREATE TABLE geocoding_queue (
id BIGSERIAL PRIMARY KEY,
address_id BIGINT REFERENCES addresses(id),
status VARCHAR(20) DEFAULT 'PENDING',
attempts INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
processed_at TIMESTAMP
);
Workers can pick up pending records.
PostgreSQL’s row-locking features can help multiple workers process jobs safely.
For example:
SELECT id
FROM geocoding_queue
WHERE status = 'PENDING'
ORDER BY id
FOR UPDATE SKIP LOCKED
LIMIT 100;
SKIP LOCKED is especially useful for queue-style workloads because multiple workers can process different rows without waiting on each other.
Step 19: Use JSONB for Flexible API Metadata
Different geocoding providers may return different fields.
For example:
{
"display_name": "Pune, Maharashtra, India",
"lat": "18.5204",
"lon": "73.8567",
"type": "city"
}
Another provider may return:
{
"formatted_address": "Pune, Maharashtra, India",
"geometry": {
"location": {
"lat": 18.5204,
"lng": 73.8567
}
}
}
Instead of creating dozens of columns for every provider-specific field, PostgreSQL’s JSONB can store additional metadata.
This gives you a structured relational model while retaining provider-specific information.
Step 20: Geocoding vs Spatial Search
These two concepts should not be confused.
Geocoding
"Pune, Maharashtra"
↓
18.5204, 73.8567
Spatial Search
18.5204, 73.8567
↓
Find locations within 10 km
The first process generally requires address intelligence or an external geocoding dataset/service.
The second is where PostGIS becomes extremely powerful.
Step 21: Building a Complete Architecture
A production-ready architecture could look like this:
Client Application
|
v
REST API
|
+------------+------------+
| |
v v
Address Cache Geocoding Queue
| |
v v
PostgreSQL Worker Service
| |
| v
| External API
| |
+------------+------------+
|
v
PostgreSQL + PostGIS
|
+----------------+----------------+
| | |
v v v
Spatial Search Distance Search Analytics
This architecture separates application requests, external API calls, and spatial database processing.
Step 22: Security Considerations
API keys should never be hardcoded inside SQL queries or frontend JavaScript.
Bad:
https://api.example.com/geocode?key=MY_SECRET_KEY
inside publicly accessible frontend code.
Instead, store secrets securely on the backend.
For example:
Frontend
|
v
Backend API
|
v
Secret / Environment Configuration
|
v
Geocoding Provider
You should also consider:
- Authentication
- Authorization
- Rate limiting
- Input validation
- HTTPS
- API-key rotation
- Request logging
- Abuse prevention
Step 23: Validate Coordinates
Applications should validate latitude and longitude before storing them.
Valid ranges are:
Latitude:
-90 to +90
Longitude:
-180 to +180
For example:
Latitude = 18.5204 ✓
Longitude = 73.8567 ✓
But:
Latitude = 250
is invalid.
Application-level validation helps prevent bad geographic data from entering the database.
Step 24: Handle Duplicate Locations
Multiple users may share the same address.
For example:
Customer A → Pune, Maharashtra
Customer B → Pune, Maharashtra
Customer C → Pune, Maharashtra
You don’t necessarily need to geocode the same address three times.
A normalized address table can help:
addresses
|
+---- address_id = 101
|
+---- Customer A
+---- Customer B
+---- Customer C
This creates a reusable geographic reference.
Step 25: Improve Performance with Spatial Indexing
For millions of records, indexes become essential.
A typical PostGIS index is:
CREATE INDEX idx_location_gist
ON addresses
USING GIST(location);
Then PostgreSQL can use spatial indexing for many operations involving geographic data.
You should always verify the query plan for important spatial queries:
EXPLAIN ANALYZE
SELECT *
FROM addresses
WHERE ST_DWithin(
location,
ST_SetSRID(
ST_MakePoint(73.8567, 18.5204),
4326
)::geography,
5000
);
This allows you to determine whether the expected index is being used.
Step 26: Common Mistakes
Mistake 1: Repeatedly Calling the Geocoding API
Don’t geocode the same address every time a user opens a page.
Use database caching.
Mistake 2: Reversing Latitude and Longitude
PostGIS generally expects:
longitude, latitude
when constructing a point.
Mistake 3: Not Creating a Spatial Index
Large geographic datasets can become slow without appropriate indexing.
Mistake 4: Calling External APIs Inside Database Transactions
External network calls can be slow and unreliable.
Keep external API communication in the application/service layer where practical.
Mistake 5: Ignoring API Rate Limits
Large imports can quickly exceed provider limits.
Use queues, workers, throttling, and retries.
Mistake 6: Storing Only Latitude and Longitude
Coordinates are useful, but PostGIS geometry/geography columns provide much richer spatial capabilities.
Mistake 7: Not Validating User Input
Malformed addresses and invalid coordinates should be handled before they enter your geographic dataset.
PostgreSQL Geocoder: Recommended Data Model
A practical design could contain:
addresses
----------------------------
id
address_text
normalized_address
city
state
country
postal_code
latitude
longitude
location
geocoding_status
geocoding_attempts
geocoded_at
metadata
created_at
updated_at
This structure provides:
- Human-readable address storage
- Geographic coordinates
- PostGIS spatial capabilities
- API metadata
- Processing status
- Retry tracking
- Audit information
Example End-to-End Workflow
Consider a delivery application.
A customer enters:
Kothrud, Pune, Maharashtra
Step 1
The application sends:
POST /geocode
Step 2
The backend normalizes the address.
kothrud, pune, maharashtra
Step 3
PostgreSQL is checked for an existing result.
Step 4
If the location exists, return the stored coordinates.
Step 5
If it does not exist, call the external geocoding API.
Step 6
Receive:
Latitude
Longitude
Address components
Step 7
Create a PostGIS point.
ST_SetSRID(
ST_MakePoint(longitude, latitude),
4326
)
Step 8
Store the result.
Step 9
Return the coordinates to the application.
Step 10
Later, the delivery application can perform:
Find all drivers within 5 km
using PostGIS.
This is where the combination becomes powerful:
Web API
+
Geocoding Service
+
PostgreSQL
+
PostGIS
=
Location-Aware Application
When Should You Build Your Own Geocoding System?
Building a complete geocoder from raw geographic datasets is significantly more complicated than simply integrating a geocoding API.
A custom system may make sense when you need:
- High-volume geocoding
- Greater control over geographic data
- Reduced dependency on a single provider
- Custom geographic datasets
- Internal/private location data
- Specialized address matching
- Offline or controlled environments
For smaller applications, using an external geocoding service while storing the results in PostgreSQL is usually much simpler.
Final Thoughts
PostgreSQL becomes a highly capable location platform when combined with PostGIS and web APIs.
The most practical architecture is not necessarily to make PostgreSQL directly call an external geocoding API. Instead, let the application or backend service handle API communication, while PostgreSQL/PostGIS manages the resulting geographic data and spatial operations.
The overall architecture can be summarized as:
ADDRESS
|
v
Backend Web API
|
v
Geocoding Provider
|
v
Latitude + Longitude
|
v
PostgreSQL + PostGIS
|
+-------+-------+
| | |
v v v
Radius Distance Nearest
Search Search Location
With proper indexing, caching, validation, asynchronous processing, and API-rate management, PostgreSQL can become the foundation of a scalable location-aware application.
The key idea is simple:
Use web APIs to translate addresses into coordinates, use PostgreSQL/PostGIS to store and manage those coordinates, and use spatial SQL to turn geographic data into useful application features.

