azure-serverless-app / README.md
README.md
Raw

Serverless Employee Profile App: Azure

Author Sharath Holla
Status PoC (working end to end through the API; browser test evidence pending)
Date 2026-10-16
Cloud Microsoft Azure, region East US
Origin Re-implementation of an AWS serverless app (S3, API Gateway, Lambda, DynamoDB)

1. Overview

A small serverless web app that saves employee profiles (ID, first name, last name, age) and lists all saved profiles. It was first built on AWS (S3 static site, REST API Gateway with GET and PUT/POST, two Python Lambda functions, one DynamoDB table employeeProfile). This project rebuilds the same app on Azure using only serverless or free-tier services, first by hand in the portal and then as Terraform.

Goals

  • Replace each AWS service with its Azure equivalent while keeping the front-end behaviour identical.
  • Keep monthly cost near zero (free tiers, scale to zero).
  • Prove the manual setup, then capture it as reproducible Terraform.

Outcomes

  • Working path: Static Web App page, API Management, Function App, Cosmos DB. The API was exercised with curl (see section 9).
  • Terraform provisions every back-end resource and publishes the function code. Remote state is stored in an existing Azure Storage blob container.
  • Findings: APIM Consumption cannot do per-IP throttling; Cosmos DB free tier is one per subscription; see section 12.

2. Architecture

Runtime architecture

Walkthrough

  1. The browser loads index.html and scripts.js from the Static Web App (Free plan). The page is deployed by an Azure DevOps pipeline.
  2. scripts.js calls the API Management (Consumption tier) gateway GET or POST /employees with jQuery AJAX. The call is cross-origin, so APIM's inbound policy answers CORS for the Static Web App origin only.
  3. APIM forwards to the Function App (<function-host>/api/employees). The API is configured with no subscription key.
  4. The Function App (Python 3.11, Flex Consumption) reads or upserts items in Cosmos DB (NoSQL API) using a connection string held in an app setting. A storage account holds the function deployment package and host state.

Design decisions

Decision Why Trade-off
Static Web Apps instead of S3 Already provisioned; free; CI/CD built in The built-in managed API (Functions) was not used because APIM is required in front of the API
Separate Function App on Flex Consumption instead of SWA managed functions APIM needs a backend URL; Flex scales to zero and has a monthly free grant Extra storage account, extra resource to manage
One Function App with two routes instead of two apps Same code size, one deployment GET and POST share a scale unit
APIM Consumption tier Serverless; first 1M calls per month free No rate-limit-by-key or quota-by-key policy (rejected by the service), no VNet integration
Cosmos DB free tier, provisioned 400 RU/s 1000 RU/s and 25 GB free Only one free-tier account per subscription; falls back to Serverless mode via a variable
Partition key /empId, item id = empId Mirrors DynamoDB's key; upsert_item equals put_item overwrite semantics GET is a cross-partition query (like DynamoDB scan); fine at this size
API open (no key), CORS locked to the site origin A key shipped in browser JavaScript is not secret Anyone can call the API directly; see section 5

3. Services and Components

Service Cloud/Tool Purpose Key configuration Cost driver
Static Web App Azure Hosts index.html, scripts.js Free plan, resource group <SHARED_RESOURCE_GROUP>, app_location: "/", api_location: "" Free
API Management Azure Public API front door Consumption_0, API path empty, operations GET /employees, POST /employees, subscription_required = false, CORS policy First 1M calls per month free, then per call
Function App Azure Business logic (get_employees, save_employee) Flex Consumption (FC1), Python 3.11, 2048 MB, max 10 instances, anonymous HTTP auth First 250k executions and 100k GB-s per month free
Storage account Azure Function package and host storage Standard LRS, private container app-package A few cents per month
Cosmos DB Azure Data store NoSQL API, Session consistency, database employeesdb, container employeeProfile, partition key /empId, 400 RU/s Free tier (1000 RU/s, 25 GB)
Azure DevOps Pipelines Azure DevOps Deploys the static site Task AzureStaticWebApp@0, triggers on main Free tier minutes
Storage account (state) Azure Terraform remote state Resource group <SHARED_RESOURCE_GROUP>, container <STATE_STORAGE_ACCOUNT>, key employee-app.tfstate Cents
Terraform HashiCorp Provisioning azurerm ~> 4.30, random ~> 3.6, null ~> 3.2, Terraform >= 1.5 None
Azure Functions Core Tools, Azure CLI CLI Code publish, auth func, az None

4. Flow Diagrams

4.1 Request and data flow

Request flow

4.2 Provisioning and CI/CD flow

Provisioning and CI/CD

Two independent deployment paths:

  • Front end: git push to main triggers the Azure DevOps pipeline, which uploads the repository root to the Static Web App.
  • Back end: terraform apply creates infrastructure. A null_resource runs func azure functionapp publish to upload the Python code; it re-runs when function_app.py or requirements.txt changes (SHA-256 trigger).

4.3 Auth/identity flow

Not a user-auth app. The browser calls the API anonymously. The Function App authenticates to Cosmos DB with the account's primary connection string (app setting COSMOS_CONNECTION_STRING). Terraform authenticates to Azure with the engineer's az login session.

4.4 Failure and recovery

Not designed for this PoC. Flex Consumption scales out to the configured maximum (10) and back to zero. There are no retries, dead-letter queues or multi-region failover.

5. Networking, Security and Identity

Network. No VNet, subnets or private endpoints. Every service is reached through its public HTTPS endpoint. CIDRs: Not applicable.

Identity and secrets

  • Function to Cosmos DB: primary connection string, stored as a Function App setting set by Terraform. It is not in Key Vault and not committed to git. It also lands in Terraform state (see below).
  • Function HTTP auth level is anonymous; only APIM is expected to call it, but the function URL is also public.
  • Terraform runs with the engineer's az login credentials.

Controls in place

  • APIM protocols = ["https"].
  • APIM inbound policy: CORS allowing only the Static Web App origin, methods GET/POST, header Content-Type.
  • Function input validation: POST requires empId, empFirstName, empLastName, empAge; returns 400 otherwise.
  • The front end builds table cells with jQuery .text(), not HTML strings, to avoid script injection from stored data.
  • Function storage container is private; blob public access disabled.
  • Function cap: 10 instances, to limit scale-out cost.

Known gaps (PoC)

  • API is unauthenticated and has no per-IP rate limit (APIM Consumption rejects rate-limit-by-key and quota-by-key). Mitigations: instance cap, an Azure budget alert (TODO: confirm one exists).
  • The Cosmos key and storage key are in Terraform state. Restrict access to the state container.
  • Encryption at rest and in transit rely on Azure platform defaults for each service. TODO: confirm no customer-managed keys are required.

6. Prerequisites

  • Azure subscription with permission to create resources and read keys; access to the existing shared resource group (<SHARED_RESOURCE_GROUP>) (Static Web App, state storage).
  • An existing Static Web App named <STATIC_WEB_APP_NAME> in <SHARED_RESOURCE_GROUP> (Terraform reads it to build the CORS origin).
  • Tools: Terraform >= 1.5, Azure CLI, Azure Functions Core Tools (func) v4, Python 3.11 for local runs (Python 3.14 is not supported by Azure Functions).
  • Authentication (below)
  • terraform/terraform.tfvars holds your values. Variables used: subscription_id, apim_publisher_email, and optionally use_cosmos_free_tier, location and others in section 8.
az login
az account set --subscription "<SUBSCRIPTION_ID>"

7. Implementation Steps

The project was built manually first (portal), then codified. These are the steps in order.

7.1 Source and decisions

Original AWS design: S3 (index.html, scripts.js with API_ENDPOINT), REST API Gateway (GET and PUT/POST), Lambda getEmployee.py (DynamoDB scan), Lambda insertEmployeeData.py (DynamoDB put_item), table employeeProfile.

7.2 Resource group

az group create --name <MANUAL_RESOURCE_GROUP> --location eastus

Screenshot pending: 01-resource-group.png

7.3 Cosmos DB

Portal: Azure Cosmos DB for NoSQL, provisioned throughput, Apply Free Tier Discount. Database employeesdb, container employeeProfile, partition key /empId, manual 400 RU/s. Copy the primary connection string.

Screenshot pending: 02-cosmos-container.png

7.4 Function App

Portal: Function App, Flex Consumption, Python 3.11, 2048 MB, Application Insights off. Add app setting COSMOS_CONNECTION_STRING.

az functionapp config appsettings set -g <MANUAL_RESOURCE_GROUP> -n <FUNCTION_APP_NAME> \
  --settings COSMOS_CONNECTION_STRING="<COSMOS_CONNECTION_STRING>"

7.5 Function code and publish

Code lives in azure_functions/ (function_app.py, host.json, requirements.txt).

cd azure_functions
python3.11 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
cp local.settings.json.sample local.settings.json   # then fill in the connection string
func start                                           # local test on :7071
func azure functionapp publish <FUNCTION_APP_NAME>   # deploy (use the app name, not the hostname)

Expected output ends with the function list: get_employees and save_employee, both at /api/employees.

Screenshot pending: 03-func-publish.png

7.6 API Management

Portal: API Management, Consumption tier. Add API, type HTTP, web service URL https://<FUNCTION_HOST>/api, empty URL suffix. Operations GET /employees and POST /employees. Untick "Subscription required". Inbound policy:

<inbound>
  <cors allow-credentials="false">
    <allowed-origins><origin>https://<STATIC_WEB_APP_HOST></origin></allowed-origins>
    <allowed-methods><method>GET</method><method>POST</method></allowed-methods>
    <allowed-headers><header>Content-Type</header></allowed-headers>
  </cors>
  <base />
</inbound>

Screenshot pending: 04-apim-test.png

7.7 Front end

index.html (form and table) and scripts.js are in the repo root. Set API_ENDPOINT in scripts.js to the APIM URL https://<APIM_NAME>.azure-api.net/employees, then push:

git add index.html scripts.js
git commit -m "Point front end at APIM"
git push

The Azure DevOps pipeline (azure-static-web-apps-<SWA_ID>.yml) deploys it.

TODO: confirm. scripts.js in the repository currently points to https://<MANUAL_APIM_NAME>.azure-api.net/employees. The Terraform-created gateway is https://<APIM_NAME>.azure-api.net/employees. Confirm which APIM instance the live site should use.

Screenshot pending: 05-browser-page.png

7.8 Codify in Terraform

See section 8.

8. Terraform Deployment

Layout

terraform/
  versions.tf               # terraform block, azurerm backend, providers
  variables.tf
  main.tf                   # all resources
  outputs.tf
  terraform.tfvars          # not committed (ignored)
  terraform.tfvars.example

Providers and backend

  • Providers: hashicorp/azurerm ~> 4.30, hashicorp/random ~> 3.6, hashicorp/null ~> 3.2; Terraform >= 1.5.
  • Remote state (azurerm backend): resource group <SHARED_RESOURCE_GROUP>, storage account <STATE_STORAGE_ACCOUNT>, container <STATE_STORAGE_ACCOUNT>, key employee-app.tfstate. Locking uses blob leases. Backend values cannot use variables.

Resources created: random_string, resource group <APP_RESOURCE_GROUP>, Cosmos account, SQL database, SQL container, storage account and private container, Flex service plan (FC1), Flex Function App, null_resource code publish, API Management (Consumption_0), API, two operations, API policy. It reads (does not create) the existing Static Web App.

Variables

Name Description Default Required
subscription_id Azure subscription ID none yes
apim_publisher_email APIM publisher email none yes
location Region eastus no
resource_group_name New resource group <APP_RESOURCE_GROUP> no
prefix Name prefix employee no
use_cosmos_free_tier Free tier, else Serverless true no
cosmos_database_name Database employeesdb no
cosmos_container_name Container employeeProfile no
apim_publisher_name APIM publisher Employee App no
static_web_app_name Existing SWA <STATIC_WEB_APP_NAME> no
static_web_app_resource_group SWA resource group <SHARED_RESOURCE_GROUP> no
deploy_function_code Run func publish from Terraform true no

Commands

cd terraform
terraform init
terraform fmt -check
terraform validate
terraform plan -out=tfplan
terraform apply tfplan

(terraform plan -var-file=<env>.tfvars if you use a named var file; this project uses terraform.tfvars, loaded automatically.)

Outputs: api_endpoint, function_app_name, function_url, cosmos_account, static_web_app_url. Use api_endpoint as API_ENDPOINT in scripts.js.

State notes. Remote state, one key. Sensitive values (connection strings, storage key) are stored in state. The null_resource publish needs az login and func on the machine running Terraform; set deploy_function_code = false to deploy code from CI instead.

Update workflow. Edit function_app.py, then terraform apply; the SHA-256 trigger re-runs the publish. To force a re-publish: terraform apply -replace='null_resource.publish_function[0]'.

Destroy

terraform destroy

Resources outside Terraform (not removed by destroy): the Static Web App and the state storage account in <SHARED_RESOURCE_GROUP>; the manually created <MANUAL_RESOURCE_GROUP> group if it still exists (az group delete -n <MANUAL_RESOURCE_GROUP>). Note the manual Cosmos account holds the single free tier; delete it before applying with use_cosmos_free_tier = true.

Screenshots pending: 06-terraform-apply.png, 07-resource-group-resources.png

9. Verification and Testing

API=https://<APIM_NAME>.azure-api.net/employees
curl -i $API                                   # list
curl -i -X POST $API -H "Content-Type: application/json" \
  -d '{"empId":"1","empFirstName":"John","empLastName":"Doe","empAge":"26"}'
curl $API                                      # list again
curl -i -X OPTIONS $API \
  -H "Origin: https://<STATIC_WEB_APP_HOST>" -H "Access-Control-Request-Method: POST"   # CORS
Check Expected output
First GET on an empty container HTTP 200, body []
POST HTTP 200, {"message": "Saved John"}
GET after save [{"empId":"1","empFirstName":"John","empLastName":"Doe","empAge":"26"}]
OPTIONS with the site origin Access-Control-Allow-Origin equals the site origin
Invalid POST body HTTP 400 with an error message

These are expected outputs. Actual run output was not captured in the repository. Screenshots pending: 08-curl-get.png, 09-curl-post.png, 10-browser-save-and-list.png.

Layer check when something fails: call the function URL directly, then the APIM URL. Function OK but APIM not means APIM config; neither means function or Cosmos.

10. Monitoring and Operations

  • Logs/metrics: Application Insights is intentionally off (cost). Failures return 500 with no logged detail. TODO: enable Application Insights or log streaming when debugging.
  • Alerts and dashboards: none configured.
  • Scaling: Flex Consumption scales 0 to 10 instances. First request after idle has a cold start of a few seconds.
  • Backup and recovery: Cosmos DB default backup policy (platform default; TODO: confirm mode). No cross-region replica.
  • Runbook
Symptom Likely cause
404 on function URL Code not published, or wrong app name passed to func publish
500 on function Missing/wrong COSMOS_CONNECTION_STRING, or database/container name mismatch
Browser CORS error APIM CORS origin does not match the site URL exactly
APIM 404 or 500 Backend URL missing /api, or function down

11. Cost and Cleanup

  • Cost drivers: Function executions and storage (free grants cover a PoC), APIM calls (1M free per month), Cosmos DB (free tier covers 400 RU/s), the function storage account (cents). Rough estimate: a few cents per month at PoC traffic. Assumes one account with free tier, no Application Insights, and low traffic.
  • Because the API has no per-IP limit, set a budget alert so abuse is noticed.
  • Teardown: terraform destroy (section 8), plus any manual leftovers listed there.

12. Challenges, Lessons Learned and Improvements

Problem Resolution
curl returned 404 on the function URL The app name is the short name; the long <random-suffix>.<region>-01 string is only the hostname suffix. Publishing with the correct name registered the functions.
Function then returned 500 The Cosmos container was named employeesdb (same as the database), but the code defaults to employeeProfile. Fixed by naming the container correctly (Terraform does this) or setting COSMOS_CONTAINER.
Terraform apply failed on the APIM policy (HTTP 400) rate-limit-by-key is not allowed on the Consumption SKU (quota-by-key is also rejected). Removed it; capped Function scale-out instead.
Only one Cosmos free tier per subscription use_cosmos_free_tier variable switches to Serverless mode.
Local Python 3.14 Not supported by Azure Functions; use 3.11.

For production

  • Authenticate the API (Entra ID or APIM subscription keys behind a backend-for-frontend), and add real throttling (APIM Standard v2/Developer tier or Azure Front Door WAF).
  • Use managed identity with Cosmos DB data-plane RBAC instead of a connection string; store remaining secrets in Key Vault.
  • Enable Application Insights, alerts and a budget.
  • Move code deployment to a pipeline and set deploy_function_code = false.
  • Replace the GET full scan with pagination.

Next experiments: manage the Static Web App in Terraform too; add a pipeline for the function code; private endpoints.

Appendix

A. Function API contract

Operation Request Success Errors
GET /employees none 200, JSON array of {empId, empFirstName, empLastName, empAge} 500
POST /employees JSON {empId, empFirstName, empLastName, empAge} 200, {"message": "Saved <first name>"} 400 missing field or empty empId

B. Repo tree

.
├── index.html                  # front end page
├── scripts.js                  # AJAX calls to APIM
├── azure-static-web-apps-<SWA_ID>.yml   # Azure DevOps pipeline
├── azure_functions/
│   ├── function_app.py
│   ├── host.json
│   ├── requirements.txt
│   └── local.settings.json.sample
├── terraform/
│   ├── versions.tf  variables.tf  main.tf  outputs.tf
│   └── terraform.tfvars.example
├── AZURE_SETUP.md              # manual setup guide
└── docs/
    ├── REPORT.md / REPORT.html / REPORT.pdf
    ├── architecture.png|svg|py
    ├── flows/  (request-flow.*, provisioning-cicd.*, sources)
    └── screenshots/

C. Open items

  • Screenshots: all marked "pending" above.
  • API_ENDPOINT mismatch between scripts.js and the Terraform APIM (section 7.7).
  • Confirm budget alert, Cosmos backup mode and encryption requirements.
  • The original AWS source files (aws_infra/) are no longer in the working tree; the AWS description in this report is from the project notes read earlier.

D. References

  • Azure Architecture Icons: learn.microsoft.com/azure/architecture/icons (rendered here with the Python diagrams library icon set)
  • Azure Static Web Apps, API Management policies by tier, Flex Consumption plan, Cosmos DB free tier (Microsoft Learn)
  • Terraform azurerm provider docs