Building location-aware booking without surprising users
A “find something nearby and book it” feature sounds simple until real users start relying on it. Locations may be closed, availability can change between search and checkout, GPS permission may be denied, and a successful network request does not necessarily mean a reservation is confirmed.
This guide walks through a practical design for a location-aware booking flow. The examples use TypeScript and a fictional venue-booking API, but the same ideas apply to restaurants, clinics, coworking spaces, classes, and other appointment-based services.
The central principle is to keep three concerns separate:
- Discovery: Which places might fit the user’s request?
- Availability: Is a particular time and party size currently bookable?
- Reservation: Has the business actually accepted and recorded the booking? Treating those as separate steps makes the product easier to reason about and reduces false confirmations. ## 1. Write down the user’s intent first Before choosing a map library or database, define the inputs that affect a useful result. A basic search might include:
- A location: coordinates, a named area, or a manually entered address.
- A radius or travel boundary.
- A category, such as a restaurant or lounge.
- A date, time, and party size when booking is involved.
- Optional preferences, such as accessibility or price range. Represent these as explicit data rather than scattered query parameters:
type SearchRequest = { latitude: number; longitude: number; radiusMeters: number; category?: string; startsAt?: string; // ISO 8601 instant partySize?: number; }; Validate values at the boundary. Latitude must between -90 and 90, longitude between -180 and 180, radius should have a sensible maximum, and party size should be a positive integer. Also validate timestamps and decide whether the product accepts the user’s local time or an explicit time zone.
That last detail matters. “7:30 PM” is not a globally unambiguous instant. Store a canonical timestamp, but retain the venue’s time zone so the interface can display the booking in local time. Daylight-saving transitions make hand-waving about time zones especially risky.
2. Ask for location at the right moment
Do not make location permission a prerequisite for opening the page. Explain why location helps, then request it after the user chooses a nearby-search action. If permission is denied, offer a usable alternative: city, district, postal code, or address search.
In a browser, the Geolocation API is asynchronous and can fail for several reasons. It may be unavailable, blocked, or time out. Handle those cases as normal outcomes rather than fatal errors:
function getCurrentPosition(): Promise<GeolocationPosition> { return new Promise((resolve, reject) => { if (!navigator.geolocation) { reject(new Error("Geolocation is unavailable")); return; } navigator.geolocation.getCurrentPosition(resolve, reject, { enableHighAccuracy: false, timeout: 8_000, maximumAge: 60_000, }); }); } High accuracy can cost time and battery. For browsing venues, a recent approximate location is often sufficient; reserve more precise positioning for cases that genuinely need it. Do not keep polling a user’s location in the background when a one-time reading will do.
On the interface, distinguish “location unavailable” from “no results.” The first calls for a manual location option; the second may call for a wider radius or different filters. Avoid silently substituting a fixed location, because that can make results look plausible while being completely wrong.
3. Model nearby search as a database query
A naïve implementation loads every venue and calculates distance in application code. That becomes expensive as the dataset grows and makes pagination awkward. Store coordinates in a spatially indexed representation and let the database narrow candidates.
For example, PostgreSQL with PostGIS can represent a venue as a geography point and use a GiST index:
CREATE INDEX venues_location_gix ON venues USING GIST (location); A distance-limited query can use ST_DWithin, which accepts meters for geography values:
SELECT id, name, ST_Distance(location, ST_SetSRID(ST_MakePoint($1, $2), 4326)::geography) AS distance_meters FROM venues WHERE active = true AND ST_DWithin( location, ST_SetSRID(ST_MakePoint($1, $2), 4326)::geography, $3 ) ORDER BY distance_meters ASC LIMIT $4; Be careful about coordinate order: many spatial functions expect longitude first, then latitude. Give parameters descriptive names and test with known locations to catch swapped values.
The query above answers “which active venues are close?” It does not prove that a venue is open or has a slot. Keep the discovery query focused, and apply availability rules in a dedicated service or query designed for the booking model.
For a small prototype without a spatial database, a bounding-box prefilter followed by a Haversine calculation can be adequate. Do not mistake that shortcut for a scalable geographic search system: bounding boxes distort near the poles, and an unindexed full scan will become costly.
4. Make ordering and pagination stable
Sorting only by distance produces ties. If two venues have the same rounded distance, their order may shift between requests, causing confusing pagination. Add a stable secondary key:
ORDER BY distance_meters ASC, id ASC For larger result sets, cursor pagination is often more robust than offset pagination. A cursor can encode the last result’s distance and ID, and the next query can continue after that pair. Sign or otherwise validate client-provided cursors; never trust arbitrary cursor values as SQL fragments.
Search results also need a clear freshness policy. Cache relatively stable venue details separately from availability. A venue’s address may change rarely, while a booking slot can disappear in seconds. Putting both behind the same long-lived cache risks displaying stale openings.
5. Treat availability as a race, not a promise
The most important booking edge case is two people trying to claim the same remaining slot. Showing availability is informational; only the reservation transaction can guarantee the outcome.
A simplified relational model might include:
venues(id, name, time_zone, ...) slots(id, venue_id, starts_at, capacity, reserved_count, ...) reservations(id, slot_id, customer_id, party_size, status, idempotency_key, ...) When a user submits a booking, perform the capacity check and reservation write atomically. One approach is a conditional update:
UPDATE slots SET reserved_count = reserved_count + $1 WHERE id = $2 AND reserved_count + $1 <= capacity RETURNING id; If no row is returned, the slot cannot accommodate the request. Run this together with reservation creation in a transaction. For more complex inventory rules, use row-level locking or a carefully designed allocation model, and test concurrent requests rather than assuming sequential behavior.
The response should distinguish states such as pending, confirmed, and rejected. If a business must manually accept a request, do not label it confirmed merely because the API stored it. Tell the user what happens next and how they will learn the final result.
6. Make retries safe with idempotency
Mobile connections fail at inconvenient moments. A user may tap “Book,” see a spinner, and retry because the response was lost. Without protection, the server could create two reservations.
Have the client send an idempotency key for each intentional submission. Persist the key alongside the result, with a uniqueness constraint scoped to the customer or account. If the same request is retried, return the original outcome rather than creating another reservation.
POST /reservations Idempotency-Key: 5e7b2f7a-... Content-Type: application/json The server should also verify that a reused key is not attached to a materially different request. Idempotency is not the same as rejecting every repeated click: it is a way to make network retries safe while preserving intentional new bookings.
7. Design useful failure states
A strong flow explains what the user can do next. Consider separate messages for:
- Location permission denied: enter an area manually.
- No venues nearby: expand the radius or change category.
- Slot just taken: choose another time and refresh availability.
- Booking pending: wait for the venue’s response.
- Network timeout: check the booking status before submitting again. Avoid showing a generic “Something went wrong” for every failure. At the same time, do not expose internal stack traces or sensitive service details. Log a correlation ID and show it only when useful for support. For a real-world example of a category-specific discovery page, Massage Hà Đông illustrates the kind of venue information a user might inspect before deciding whether to contact or book a place. The engineering point is broader than any one directory: a listing should help people evaluate fit, while the reservation system remains authoritative about availability and confirmation. ## 8. Keep the API contract explicit A search endpoint might accept a validated query such as:
GET /venues?lat=21.0&lng=105.8&radius=5000&category=restaurant Return only information needed for discovery, with units and semantics documented:
{ "items": [ { "id": "venue_123", "name": "Example Place", "distanceMeters": 820, "location": { "latitude": 21.0, "longitude": 105.8 } } ], "nextCursor": null } Do not make clients infer whether distance is miles or meters, whether coordinates are rounded, or whether the result says anything about a specific booking time. For booking, use a separate endpoint with a request schema that includes the chosen slot, party size, and idempotency key.
Rate-limit expensive search and reservation endpoints appropriately. Validate input on the server even if the client already validates it. Keep secrets and internal identifiers out of public responses, and avoid logging precise user coordinates longer than the feature requires. Location data can be sensitive; collect the minimum needed and make retention practices deliberate.
9. Test the awkward cases
A useful test plan covers more than the happy path:
- Invalid coordinates and excessive radius values.
- Permission denied, unavailable geolocation, and timeout.
- A venue exactly on the radius boundary.
- Correct coordinate order and distance units.
- Empty results and stable pagination.
- Two concurrent requests for the last available capacity.
- Retrying the same request with the same idempotency key.
- Reusing a key with a conflicting payload.
- Daylight-saving changes and venues in different time zones.
- A booking that remains pending rather than becoming confirmed. For concurrency behavior, run integration tests against the actual database engine. Mock-based unit tests are valuable for business rules, but they cannot prove that transaction isolation and locking behave as expected in production. ## 10. Measure outcomes, not just clicks Useful operational measures include search latency, search-to-detail transitions, reservation submission failures, duplicate-prevention hits, and the time a pending request takes to reach a final state. Break down errors by category and client version, but avoid retaining raw location history merely to produce analytics. A location-aware booking feature is successful when users can find relevant options, understand what is available, and know whether a reservation is real. That outcome depends less on a clever map screen than on clear data contracts, sound spatial queries, concurrency-safe inventory, and honest status messages. Start with those foundations; add maps, recommendations, and richer filters only when they improve a specific part of the user journey.