Azure Functions Pocket Book


Azure Functions Pocket Book — Uplatz

55+ deep-dive flashcards • Single column • Triggers & Bindings • Durable Functions • Dev/Deploy • Performance & Security • Interview Q&A

Cheat-friendly explanations • Readable CLI/SDK snippets • Production-oriented tips

Section 1 — Fundamentals

1) What is Azure Functions?

Event-driven, serverless compute. Write small functions that run on triggers (HTTP, queue, timer, events). You manage code; Azure manages servers & scaling.

# Check Core Tools
func --version
az extension add -n azure-dev

2) Hosting Plans

Consumption (pay per execution, true serverless), Premium (pre-warmed, VNET, no cold start), Dedicated/App Service (reserved). Choose by latency/VNET/cost.

3) Languages & Runtimes

C#, JavaScript/TypeScript, Python, Java, PowerShell, Custom Handlers. Function runtime versions align with language workers.

4) Triggers & Bindings

Triggers start your function; input/output bindings connect to services (Storage, Service Bus, Cosmos DB, SignalR). No SDK boilerplate for common I/O.

5) Function App Structure

A Function App hosts one or more functions sharing a runtime & settings. Each function has function.json describing its bindings.

func init myapp --worker-runtime node
cd myapp
func new --name httpHello --template "HTTP trigger"

6) When to Use

Lightweight APIs, event processing, schedulers, glue code, ETL steps, webhooks. Not ideal for long CPU-bound tasks—offload to containers/jobs.

7) Pricing Basics

Consumption charges = executions + GB-s + outbound. Premium = instance uptime + executions. Watch networking egress and storage transactions.

8) Cold Starts

Cold start = first request spins up worker. Premium plan pre-warms to avoid. For HTTP on Consumption, use “Always On” with APIM ping or warmers (non-critical).

Section 2 — Triggers & Bindings (with Snippets)

9) HTTP Trigger

Quick APIs or webhooks. Auth levels: anonymous, function, admin.

// JavaScript (index.js)
module.exports = async function (context, req) {
  const name = (req.query.name || (req.body && req.body.name) || "world");
  context.res = { body: `Hello, ${name}!` };
};

// function.json (excerpt)
{
  "bindings":[
    {"authLevel":"function","type":"httpTrigger","direction":"in","name":"req","methods":["get","post"]},
    {"type":"http","direction":"out","name":"res"}
  ]
}

10) Timer Trigger

CRON schedules for cleanup or reports.

{
  "schedule": "0 0 6 * * *", "type":"timerTrigger","direction":"in","name":"myTimer"
}

11) Queue Storage Trigger

Fires on new messages; use poison queue for failed retries.

{
  "type":"queueTrigger","name":"msg","queueName":"tasks","connection":"AzureWebJobsStorage","direction":"in"
}

12) Service Bus Trigger

For enterprise messaging (queues/topics).

{
  "type":"serviceBusTrigger","name":"sbMsg","queueName":"orders","connection":"ServiceBusConn","direction":"in"
}

13) Event Grid Trigger

React to resource events (Blob created, custom events) with durable delivery and retries.

14) Event Hubs Trigger

High-throughput streaming ingestion; tune batch size & checkpointing for throughput.

15) Blob Trigger

ETL pipelines on file drops (e.g., convert images, parse CSV).

16) Cosmos DB Trigger

React to inserts/updates on a collection for projections/denormalization.

17) Output Bindings

Write to queues/blobs/tables/SignalR without SDK glue.

{
  "bindings":[
    {"type":"httpTrigger","name":"req","direction":"in"},
    {"type":"queue","name":"outMsg","queueName":"tasks","connection":"AzureWebJobsStorage","direction":"out"}
  ]
}

Section 3 — Local Dev & Tooling

18) Core Tools & Emulator

Install Azure Functions Core Tools and Azurite (Storage emulator) for local triggers.

npm i -g azure-functions-core-tools@4
npm i -g azurite
azurite &   # start storage emulator
func start  # run functions locally

19) local.settings.json

Local-only configuration for connection strings and app settings (not deployed).

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "node"
  }
}

20) VS Code Extension

Scaffolds functions, debugs breakpoints, deploys with one click. Pair with Azure CLI for auth.

21) function.json & host.json

function.json defines bindings; host.json controls runtime (concurrency, logging, batching).

{
  "version":"2.0",
  "logging": {"applicationInsights":{"samplingSettings":{"isEnabled":true,"maxTelemetryItemsPerSecond":5}}},
  "extensions": {"serviceBus": {"maxConcurrentCalls": 16}}
}

22) Python Example

# __init__.py
import logging
def main(req):
    name = (req.params.get('name') or 'world')
    return f"Hello, {name}!"

Section 4 — Deployment & Config

23) Zip Deploy + Run From Package

Immutable deployments increase reliability.

func azure functionapp publish my-func-app --typescript --publish-local-settings -i
# or
az functionapp deployment source config-zip -g rg -n my-func-app --src package.zip

24) GitHub Actions

# .github/workflows/deploy.yml (Node)
- uses: actions/setup-node@v4
- run: npm ci && npm run build
- uses: Azure/functions-action@v1
  with:
    app-name: my-func-app
    package: '.'

25) App Settings & Key Vault

Use Key Vault references (@Microsoft.KeyVault(...)) and managed identity; never hardcode secrets.

26) Slots

Staging slots allow safe swaps; mark connection strings as “slot setting” if they differ.

27) Containerized Functions

Package as a Linux container to control dependencies; supports Premium/Dedicated.

FROM mcr.microsoft.com/azure-functions/node:4-node18
COPY . /home/site/wwwroot

28) VNET Integration

Required to reach private endpoints (databases, storage). Premium plan recommended for stable connections.

Section 5 — Performance, Scaling & Reliability

29) Concurrency & Batching

Tune Service Bus/Event Hub batch sizes; use parallelism for CPU-light handlers; beware long CPU sections—offload.

30) Retries & Poison

Storage queues have poison queues; Service Bus has DLQ. Configure retry policies in host.json or bindings.

31) Timeouts & Memory

Default timeout varies by plan (Consumption has limits). Use Premium for longer processing. Keep memory steady—avoid big in-memory buffers.

32) Idempotency

Make handlers safe to retry. Use dedupe IDs, ETags, or state checks to avoid duplicate side effects.

33) Parallel Fan-out

For many independent tasks, queue messages and process concurrently. For orchestrations, consider Durable Functions.

Section 6 — Security

34) Auth Levels

HTTP trigger authLevel: anonymous, function (requires key), admin (master key). Prefer Azure AD / APIM for production APIs.

35) Azure AD Protection

Enable “Easy Auth” (App Service Authentication) or front with APIM/Front Door and validate JWT scopes/roles.

36) Managed Identity

Access Storage, Key Vault, Cosmos DB without secrets via MSI and RBAC.

az functionapp identity assign -g rg -n my-func-app
az role assignment create --assignee <principalId> --role "Storage Blob Data Reader" --scope <storage-scope>

37) Private Endpoints

Lock down function ingress with Private Endpoints + Application Gateway/Front Door for external publishing.

Section 7 — Observability

38) Application Insights

Built-in logging, metrics, live metrics, sampling. Correlate traces across services.

# host.json logging sample above; also configure APPINSIGHTS_CONNECTIONSTRING

39) Structured Logs

Use ILogger (C#) / context.log (JS) with consistent fields. Don’t log secrets or large payloads.

40) Alerts & Dashboards

Alerts on failure rate, function duration, 5xx, queue backlog. Pin charts in Azure Dashboard for on-call.

Section 8 — Durable Functions (Orchestrations)

41) What is Durable Functions?

State orchestration on top of Functions. Patterns: function chaining, fan-out/fan-in, async HTTP APIs, human interaction, sagas.

42) Orchestrator Constraints

Orchestrators must be deterministic—no random time.now or non-deterministic I/O. Use context.currentUtcDateTime and activity functions.

43) Sample (JS)

// orchestration.js
const df = require("durable-functions");
module.exports = df.orchestrator(function* (context) {
  const items = yield context.df.callActivity("GetItems");
  const results = yield context.df.callSubOrchestrator("ProcessItems", items);
  return results.length;
});

44) Durable Entities

Lightweight stateful objects (counters, carts). Access via signals; good for per-key coordination.

45) Human Interaction

External events pause orchestration until approval; combine with timeouts and compensating actions (saga).

Section 9 — Patterns, Gotchas & Interview Q&A

46) Pattern — API + Queue

HTTP receives request → enqueue job → immediate 202 response → worker processes async → client polls status endpoint.

47) Pattern — ETL on Blob

Blob trigger parses file → writes cleaned data to Data Lake → Event Grid notifies downstream.

48) Common Pitfall — Large Files

Don’t buffer whole files in memory. Stream to Storage/Bus; use temp files on /home if needed; consider durable patterns.

49) Common Pitfall — Long Work

Hitting timeout? Move to Durable, break into activities, or offload to containerized batch jobs.

50) Interview — Functions vs Logic Apps?

Answer: Functions = code-first, flexible; Logic Apps = designer-first workflows & connectors. Often used together.

51) Interview — Consumption vs Premium?

Answer: Consumption is cheapest but can have cold start & limits; Premium offers pre-warmed instances, VNET, longer timeouts.

52) Interview — Mitigate cold start?

Answer: Premium pre-warmed, smaller bundles, keep warm pings (non-critical), avoid heavy startup, use DI & lazy init.

53) Interview — Ensuring idempotency?

Answer: Use message IDs, de-dup tables, blob ETags, and transactional outbox; handle retries safely.

54) Troubleshoot Failures

Check App Insights traces, “Function execution” logs, DLQs/poison queues, Kudu console, and recent deployments for config drift.

55) Production Checklist

CI/CD with run-from-package, slots & swaps, Key Vault refs, MSI + RBAC, private endpoints/VNET, alerts & dashboards, lifecycle docs & runbooks.