Project 2: Serverless Order Processing on Azure with Functions, Service Bus, Cosmos DB, Static Web Apps and Front Door
Architecture
text
Browser -> Static Web App (HTML/JS)
| POST /api/orders
Function A (HTTP trigger) -> validates -> Service Bus queue "orders"
|
Function B (Service Bus trigger)
|
Cosmos DB (orders container)
|
change feed -> Function C -> email/notificatio
- Why queue in the middle? The web request returns quickly, spikes are absorbed and failed messages go to the dead-letter queue
- All services use managed identity. No connection string secrets in code
Step 1: Create Resources
bash
az group create -n rg-serverless -l centralindia
az servicebus namespace create -g rg-serverless -n sbsl482 --sku Standard
az servicebus queue create -g rg-serverless --namespace-name sbsl482 -n orders --max-delivery-count 5
az cosmosdb create -g rg-serverless -n cosmossl482 --capabilities EnableServerless --default-consistency-level Session
az cosmosdb sql database create -g rg-serverless -a cosmossl482 -n shop
az cosmosdb sql container create -g rg-serverless -a cosmossl482 -d shop -n orders --partition-key-path /customerId
az storage account create -g rg-serverless -n stslfunc482 --sku Standard_LRS
az monitor app-insights component create -g rg-serverless -a ai-serverless -l centralindia --kind web
az functionapp create -g rg-serverless -n func-orders-482 --storage-account stslfunc482 --consumption-plan-location centralindia \
--runtime python --runtime-version 3.11 --functions-version 4 --os-type Linux --assign-identity [system] --app-insights ai-serverless
Step 2: Permissions Without Secrets
bash
PID=$(az functionapp identity show -g rg-serverless -n func-orders-482 --query principalId -o tsv)
az role assignment create --assignee $PID --role "Azure Service Bus Data Owner" --scope $(az servicebus namespace show -g rg-serverless -n sbsl482 --query id -o tsv)
az cosmosdb sql role assignment create -g rg-serverless -a cosmossl482 --role-definition-name "Cosmos DB Built-in Data Contributor" --principal-id $PID --scope "/"
az functionapp config appsettings set -g rg-serverless -n func-orders-482 --settings "ServiceBusConnection__fullyQualifiedNamespace=sbsl482.servicebus.windows.net"
Step 3: Function Code (Python v2 model)
python
import json, logging
import azure.functions as func
from azure.identity import DefaultAzureCredential
from azure.cosmos import CosmosClient
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
@app.route(route="orders", methods=["POST"])
@app.service_bus_queue_output(arg_name="msg", queue_name="orders", connection="ServiceBusConnection")
def create_order(req: func.HttpRequest, msg: func.Out[str]) -> func.HttpResponse:
try:
order = req.get_json()
if not order.get("customerId") or order.get("total", 0) <= 0:
return func.HttpResponse("Invalid order", status_code=400)
except ValueError:
return func.HttpResponse("Bad JSON", status_code=400)
msg.set(json.dumps(order))
return func.HttpResponse("Accepted", status_code=202)
cosmos = CosmosClient("https://cosmossl482.documents.azure.com:443/", credential=DefaultAzureCredential())
container = cosmos.get_database_client("shop").get_container_client("orders")
@app.service_bus_queue_trigger(arg_name="m", queue_name="orders", connection="ServiceBusConnection")
def save_order(m: func.ServiceBusMessage):
order = json.loads(m.get_body().decode())
order["id"] = m.message_id
container.upsert_item(order) # upsert = safe if the message is retried
logging.info("Saved order %s", order["id"])
Idempotency A message can be delivered more than once. Using upsert with a stable id means a retry does not create duplicates.
Step 4: Deploy and Test
bash
func azure functionapp publish func-orders-482
KEY=$(az functionapp function keys list -g rg-serverless -n func-orders-482 --function-name create_order --query default -o tsv)
curl -X POST "https://func-orders-482.azurewebsites.net/api/orders?code=$KEY" -H "Content-Type: application/json" -d '{"customerId":"c42","total":799}'
# Check data in Cosmos DB Data Explorer and logs in Application Insights
Step 5: Front End and Global Entry
- Host the HTML/JS page on Azure Static Web Apps (connect a GitHub repo; it deploys with a workflow). Link the Function App as its API backend
- For custom domain, caching and WAF, place Azure Front Door in front
- Restrict Function access with Entra authentication or APIM instead of function keys for real users
Step 6: Failure and Scale Tests
- Send 1,000 orders quickly. Watch Function instances scale out
- Make
save_orderthrow for a bad order. After 5 tries the message lands in the dead-letter queue - Check Application Insights for failures and end-to-end traces
Review
| Pillar | Notes |
|---|---|
| Reliability | Queue buffers spikes, retries and dead-letter, add zone redundancy and geo-DR for production |
| Security | Managed identities, RBAC roles, private endpoints with Premium plan if needed |
| Cost | Consumption plan and Cosmos serverless: pay per use |
| Operations | App Insights, alerts on dead-letter count, IaC and CI/CD |
| Performance | Partition key /customerId, tune concurrency, watch cold starts |
Clean Up
bash
az group delete -n rg-serverless --yes --no-wait
Conclusion
You built an event-driven serverless app: an HTTP Function puts orders on Service Bus, a second Function saves them to Cosmos DB with managed identity, with a Static Web App front end and monitoring.
Quick Summary: architecture; resources; identity; code; deploy; front end; tests; review.

