AWS Builder Center

Your Mobile App Doesn't Need to Send Every Location Update: Building a Cost-Aware Location API with AWS

A practical guide to building an intelligent, serverless location-ingestion pipeline using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB.

Introduction

Imagine building a mobile application that allows users to share their live locations with friends.
Every few seconds, the application receives a new GPS coordinate. It sends that coordinate to the backend, which processes the request and stores the latest location in a database.
Initially, everything works perfectly.
But as the number of users increases, a problem emerges.
A user might remain stationary for several minutes while the application continues sending nearly identical coordinates. The backend receives unnecessary requests, performs redundant database operations, and consumes resources without providing meaningful value.
The problem isn't that the application needs more infrastructure.
The problem is that it needs to be smarter about the data it sends.
In this tutorial, we'll build a serverless location-ingestion API that filters insignificant location changes before storing them. We'll use AWS managed services to create a backend that is scalable, maintainable, and cost-conscious.

1. Understanding the architecture

We'll use three primary AWS services:
  • Amazon API Gateway: Receives HTTP requests from the mobile application.
  • AWS Lambda: Processes incoming coordinates and determines whether an update should be stored.
  • Amazon DynamoDB: Stores the latest meaningful location for each user.
Our request flow will look like this:
Mobile Application
|
| Location Update (JSON)
v
Amazon API Gateway
|
v
AWS Lambda
|
v
Check Previous Location
|
v
Calculate Distance
|
+------ Insignificant Movement
| |
| v
| Ignore
|
+------ Significant Movement
|
v
Amazon DynamoDB
|
v
API Response
The important part is that the filtering happens before unnecessary database writes.

2. Creating the DynamoDB table

First, create a DynamoDB table named  UserLocations .
Configure the following:
Setting
Value
Table name
UserLocations
Partition key
user_id
Partition key type
String
Billing mode
On-demand
We'll store the latest accepted location for each user.
A sample record looks like this:
{
"user_id": "user_101",
"latitude": 13.0827,
"longitude": 80.2707,
"accuracy": 12.5,
"updated_at": 1793620000
}
Using a partition key based on the user ID allows us to retrieve a user's latest location directly.

3. Building the Lambda function

Create a Python Lambda function.
We'll use the Haversine formula to calculate the approximate distance between two GPS coordinates.
This is important because comparing latitude and longitude directly does not tell us the actual distance travelled.
The Haversine formula calculates the great-circle distance between two points on Earth.

Distance calculation

import math

def calculate_distance(lat1, lon1, lat2, lon2):
earth_radius = 6371000

lat1 = math.radians(lat1)
lat2 = math.radians(lat2)

delta_lat = math.radians(lat2 - lat1)
delta_lon = math.radians(lon2 - lon1)

a = (
math.sin(delta_lat / 2) ** 2
+ math.cos(lat1)
* math.cos(lat2)
* math.sin(delta_lon / 2) ** 2
)

c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

return earth_radius * c
The function returns the distance in meters.
For example, if the previous location and incoming location are only 8 meters apart, we might decide that the movement is insignificant.
For this demonstration, we'll use a movement threshold of 100 meters.
We'll also accept an update if five minutes have passed since the last stored location, even if the user hasn't moved significantly. This prevents location data from becoming indefinitely stale.

4. Implementing the location-ingestion logic

Now let's connect our filtering logic to DynamoDB.
We'll use the AWS SDK for Python, Boto3.
import json
import os
import time
import boto3

from decimal import Decimal

dynamodb = boto3.resource("dynamodb")

table = dynamodb.Table(
os.environ["TABLE_NAME"]
)

MOVEMENT_THRESHOLD = 100
MAX_UPDATE_INTERVAL = 300

def lambda_handler(event, context):

try:
body = json.loads(event.get("body") or "{}")

user_id = body["user_id"]
latitude = float(body["latitude"])
longitude = float(body["longitude"])
accuracy = float(body["accuracy"])

if (
not user_id
or not -90 <= latitude <= 90
or not -180 <= longitude <= 180
or not 0 <= accuracy <= 10000
):
raise ValueError("Invalid location data")

current_time = int(time.time())

response = table.get_item(
Key={"user_id": user_id}
)

previous = response.get("Item")

should_update = True

if previous:
distance = calculate_distance(
float(previous["latitude"]),
float(previous["longitude"]),
latitude,
longitude
)

elapsed = (
current_time - int(previous["updated_at"])
)

should_update = (
distance >= MOVEMENT_THRESHOLD
or elapsed >= MAX_UPDATE_INTERVAL
)

if not should_update:
return {
"statusCode": 200,
"body": json.dumps({
"message": "Location unchanged",
"stored": False
})
}

item = {
"user_id": user_id,
"latitude": Decimal(str(latitude)),
"longitude": Decimal(str(longitude)),
"accuracy": Decimal(str(accuracy)),
"updated_at": current_time
}

table.put_item(Item=item)

return {
"statusCode": 200,
"body": json.dumps({
"message": "Location updated",
"stored": True
})
}

except (ValueError, KeyError, TypeError):
return {
"statusCode": 400,
"body": json.dumps({
"error": "Invalid request"
})
}
This is a simplified demonstration of the filtering algorithm. For concurrent production traffic, replace the read-then-write operation with an atomic conditional update, and add authentication and request ownership checks.
The key takeaway is that our application no longer needs to persist every incoming coordinate.

5. Connecting API Gateway

Next, create an HTTP API in Amazon API Gateway.
Configure a route:
POST /location
Connect this route to the Lambda function using Lambda proxy integration.
Our mobile application can now send a request like this:
{
"user_id": "user_101",
"latitude": 13.0827,
"longitude": 80.2707,
"accuracy": 12.5
}
A successful update returns:
{
"message": "Location updated",
"stored": true
}
If the movement is insignificant:
{
"message": "Location unchanged",
"stored": false
}
The mobile application can use this response to understand whether the backend accepted the update.

6. Configuring permissions

Lambda needs permission to access DynamoDB.
Create an IAM execution role for the Lambda function and grant it only the necessary permissions.
For this example, the required actions are:
  •  dynamodb:GetItem 
  •  dynamodb:PutItem 
Restrict the resource to the ARN of the  UserLocations  table.
Avoid granting broad permissions such as  dynamodb:*  or  AdministratorAccess .
Least-privilege permissions are an important part of building secure serverless applications.

7. Testing the implementation

Let's consider three scenarios.
Scenario
Expected result
User moves 150 meters
Store location
User moves 10 meters after 30 seconds
Ignore update
User stays stationary for 5 minutes
Store fresh location
Test the API using Postman or curl.
curl -X POST YOUR_API_ENDPOINT/location \
-H "Content-Type: application/json" \
-d '{
"user_id": "user_101",
"latitude": 13.0827,
"longitude": 80.2707,
"accuracy": 12.5
}'
Use Amazon CloudWatch to inspect Lambda execution logs, errors, and invocation metrics.
Testing should also include invalid coordinates, repeated requests, stale timestamps, and concurrent updates before treating the implementation as production-ready.

8. What happens when the application scales?

One advantage of this architecture is that we don't need to provision and manage traditional application servers.
AWS Lambda executes our processing code in response to incoming requests, while DynamoDB provides managed database capacity.
However, serverless doesn't automatically mean unlimited or free.
We still need to consider:
  • Lambda execution duration and memory allocation.
  • API Gateway request volume.
  • DynamoDB read and write capacity consumption.
  • CloudWatch logging costs.
  • Authentication and abuse prevention.
  • Cold starts and concurrent requests.
For larger machine learning workloads or complex geospatial queries, we may also need a different architecture.
The objective isn't to use Lambda for everything. It's to use the right service for the workload.

9. Conclusion

Building scalable applications isn't always about processing more data or adding more infrastructure.
Sometimes, the better engineering decision is to avoid processing unnecessary data in the first place.
By combining Amazon API Gateway, AWS Lambda, and DynamoDB, we've created a simple serverless architecture that filters insignificant location changes before persisting them.
This pattern can be adapted to several other applications, including delivery tracking, fitness applications, vehicle monitoring, and location-sharing platforms.
The broader lesson is simple:
A scalable system isn't just one that handles more requests. It's one that knows which requests actually matter.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article