
How to Capture Website Leads with Amazon API Gateway, AWS Lambda, and DynamoDB
Build a website lead-capture API with API Gateway, Lambda, and DynamoDB. Validate enquiries, handle duplicate submissions, and recover safely from failed requests.
A visitor submits an enquiry on your website. The browser waits, the connection times out, and the visitor clicks Submit again.
Did you receive one lead, two leads, or none?
This is a common problem in website lead capture. A form can look simple while its backend still loses enquiries, creates duplicates, or displays success before anything has been saved.
In this walkthrough, we design a small lead-capture service using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB. The focus is reliable submission handling: validate the request, store it once for a given submission identifier, and return a response the frontend can use correctly.
1. Define What “Lead Received” Means
For this example, a successful submission means the enquiry has been saved in DynamoDB.
It does not mean:
- A sales representative has reviewed it.
- A notification email has arrived.
- The lead has reached an external CRM.
- The prospect has been qualified.
These are separate stages.
The website should display “Your enquiry has been received” only after the storage operation succeeds or the backend confirms an identical submission already exists.
This gives the frontend a clear rule and prevents a notification failure from being mistaken for a lost enquiry.
2. Map the Request Flow
The service has three main components.
Component | Responsibility |
|---|---|
Amazon API Gateway HTTP API | Expose a POST /leads endpoint and forward requests |
AWS Lambda | Parse input, validate fields, and apply submission rules |
Amazon DynamoDB | Persist the enquiry and prevent replacement of an existing submission |
CloudWatch supports troubleshooting through operational logs and metrics.
The browser sends JSON to the API. Lambda validates the request and writes the lead. The API returns a success response only after persistence.
Keep sales notifications outside this initial write path. A notification outage should not stop the website from receiving enquiries.
3. Give Each Submission a Stable Identifier
Generate a random submission identifier in the browser when the visitor begins a submission attempt.
For example:
const submissionId = crypto.randomUUID();Reuse that identifier when retrying the same payload after a timeout.
Do not generate a new identifier for every network retry. Otherwise, the backend sees each retry as a new enquiry.
A request might contain:
{ "submissionId": "a04b7128-d27e-4364-97be-52c2f9ed22ac", "name": "Alex", "email": "alex@example.com", "message": "We need a CRM for our sales team."}Once the user receives success, a genuinely new enquiry should receive a new identifier.
If the visitor changes the enquiry after a failed attempt, treat the changed payload as a new submission. Reusing an old identifier for different content should produce a conflict.
This mechanism prevents duplicates caused by retries with the same identifier. It does not detect every repeated enquiry from the same person.
4. Validate on the Server
Browser validation improves usability, but anyone can call a public endpoint without using your form.
Lambda must validate the payload independently.
For a small enquiry form, define:
- A maximum request-body size.
- Required fields and accepted data types.
- Length limits for names and messages.
- A basic email-format check.
- An allowed submission-ID format.
- Which fields the application will store.
An email-format check does not prove the address exists or belongs to the sender.
Avoid accepting internal fields such as
assignedTo , qualified , or salesStatus from the public request. Set those values on the server.When showing enquiries in an internal dashboard, render submitted text safely. Input validation does not replace output escaping.
5. Store the Lead with a Conditional Write
Create a DynamoDB table with a string partition key named
submissionId .Configure a Python Lambda function with a
LEADS_TABLE environment variable containing the table name. Connect it to an API Gateway HTTP API using Lambda proxy payload format version 2.0.The following example demonstrates validation, conditional persistence, and handling an identical retry.
import base64import hashlibimport jsonimport loggingimport osimport re
from datetime import datetime, timezonefrom uuid import UUID
import boto3from botocore.exceptions import ClientError
table = boto3.resource("dynamodb").Table( os.environ["LEADS_TABLE"])logger = logging.getLogger()logger.setLevel(logging.INFO)
def response(status, payload): return { "statusCode": status, "headers": { "Content-Type": "application/json", "Cache-Control": "no-store" }, "body": json.dumps(payload) }
def lambda_handler(event, context): try: body = event.get("body") or ""
if not isinstance(body, str): raise ValueError()
raw = ( base64.b64decode(body, validate=True) if event.get("isBase64Encoded") else body.encode("utf-8") )
if len(raw) > 16_384: return response(413, {"error": "Request too large"})
data = json.loads(raw)
if not isinstance(data, dict): raise ValueError()
fields = ("submissionId", "name", "email", "message")
if any( not isinstance(data.get(field), str) for field in fields ): raise ValueError()
submission_id = str(UUID(data["submissionId"])) name = data["name"].strip() email = data["email"].strip() message = data["message"].strip()
if not 1 <= len(name) <= 120: raise ValueError()
if not 1 <= len(message) <= 4000: raise ValueError()
if ( len(email) > 254 or not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email) ): raise ValueError()
except (ValueError, TypeError, UnicodeError): return response(400, {"error": "Invalid enquiry fields"})
normalized = { "name": name, "email": email, "message": message }
canonical = json.dumps( normalized, sort_keys=True, separators=(",", ":"), ensure_ascii=False )
payload_hash = hashlib.sha256( canonical.encode("utf-8") ).hexdigest()
item = { "submissionId": submission_id, **normalized, "payloadHash": payload_hash, "createdAt": datetime.now(timezone.utc).isoformat(), "status": "NEW", "source": "website-enquiry" }
try: table.put_item( Item=item, ConditionExpression=( "attribute_not_exists(submissionId)" ) )
except ClientError as error: code = error.response["Error"]["Code"]
if code != "ConditionalCheckFailedException": logger.error( "Lead write failed requestId=%s code=%s", context.aws_request_id, code ) return response( 503, {"error": "Please retry shortly"} )
try: existing = table.get_item( Key={"submissionId": submission_id}, ConsistentRead=True ).get("Item")
except ClientError: return response( 503, {"error": "Please retry shortly"} )
if not existing: return response( 503, {"error": "Please retry shortly"} )
if existing.get("payloadHash") != payload_hash: return response( 409, {"error": "Submission identifier conflict"} )
return response(200, {"received": True})
return response(201, {"received": True})The conditional write is the key persistence safeguard. It prevents a request from replacing an existing item with the same submission identifier.
When that identifier already exists, the function reads the saved item and compares payload hashes. An identical retry receives success; different content receives a conflict.
The hash supports comparison. It does not encrypt the enquiry.
This is a starting implementation. Add deployment configuration, abuse controls, and integration tests before exposing it publicly.
6. Make the Frontend Handle Uncertainty
A timeout does not prove that a write failed.
The database might have accepted the enquiry before the response was interrupted. The frontend should retain the same submission identifier and payload when retrying.
Response | Frontend behaviour |
|---|---|
201 | Show confirmation; the enquiry was newly stored |
200 | Show confirmation; the identical submission already exists |
400 | Ask the visitor to correct the fields |
409 | Explain the submission conflict and start a new submission attempt |
413 | Ask the visitor to shorten the enquiry |
429 or temporary server error | Preserve the enquiry and retry with backoff |
Disable the Submit button while a request is in progress for usability. Backend duplicate handling remains necessary even with that button disabled.
Avoid aggressive retry loops. Use a limited number of retries with increasing delays.
7. Configure Access and Abuse Controls
For browser access, configure HTTP API CORS for your actual website origins, the
POST method, and required headers.CORS controls browser behaviour. It does not authenticate callers or prevent scripts and bots from sending requests directly.
A public enquiry endpoint also needs an abuse strategy:
- Configure API throttling and monitor rejected traffic.
- Set concurrency and budget controls appropriate to the workload.
- Consider a bot challenge with server-side token verification.
- Limit accepted fields and payload sizes.
- Monitor sudden changes in request volume.
Do not embed AWS credentials or a supposed secret API key in frontend JavaScript.
Give the Lambda execution role only the required table permissions, including
PutItem and GetItem , plus appropriate logging permissions. Keep internal lead-reading tools behind authentication and authorization.8. Add Notifications After Persistence
Once lead capture works, add a separate notification or CRM-integration path.
For example, a DynamoDB Streams consumer can process newly inserted enquiries and create a sales task.
Design that consumer for repeated delivery. Use the submission identifier as a stable reference when the destination supports idempotency.
Track integration progress separately:
-
PENDING
-
DELIVERED
-
FAILED
Define retry limits, failure handling, and a reconciliation process for stored enquiries that never reached the destination.
A saved lead and a delivered sales notification are different outcomes. Your monitoring should show both.
9. Test the Failure Scenarios
Test | Expected result |
|---|---|
Valid enquiry | One item stored; success returned |
Same identifier and same payload submitted twice | One item remains; both attempts receive success |
Concurrent identical submissions | One write wins; the retry is recognised |
Same identifier with different content | Conflict returned; saved item unchanged |
Invalid JSON or missing fields | Request rejected |
Database write failure | No success response |
Timeout after successful persistence | Retry confirms the existing enquiry |
Notification failure | Stored enquiry remains available for recovery |
Public request includes internal sales fields | Those fields are ignored |
Inspect logs during testing. Names, email addresses, enquiry text, and full request bodies should not appear in routine operational logs.
Also test how staff retrieve leads. This table supports lookup by submission identifier; a sales inbox filtered by date, owner, or status needs an additional access pattern or a CRM integration.
Conclusion
Reliable website lead capture depends on clear persistence rules and careful retry handling.
Use API Gateway to receive the request, Lambda to validate it, and DynamoDB to store it conditionally. Keep the same identifier across retries, confirm persistence before showing success, and monitor downstream delivery separately.
That gives the visitor a dependable submission experience and the sales team a recoverable record of each accepted enquiry.
Technical reference basis: AWS documentation for HTTP API Lambda proxy integrations, DynamoDB PutItem, and condition expressions. The example requires deployment and integration testing.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article