
Serverless computing lets you run code without provisioning or managing servers, paying only when that code executes. For a lean engineering team in Nairobi handling spiky traffic such as payment callbacks, end-of-month reporting or campaign-driven traffic, that can remove a lot of operational work. It also introduces new constraints around cold starts, execution limits, cost at scale and debugging. This guide explains how serverless actually works, shows a small production-style example, and gives you a checklist for deciding when it is the wrong tool.
Key takeaways
- "Serverless" means the provider manages servers, scaling and patching. You deploy functions or containers and pay per request and per unit of compute time.
- It shines for event-driven, bursty and low-to-moderate volume workloads such as webhooks, M-Pesa callbacks, file processing and scheduled jobs.
- Cold starts add latency to the first request after a period of inactivity. Runtime choice, package size and provisioned capacity all affect them.
- At sustained high volume, serverless can cost more than containers or VMs. Model the crossover point before committing.
- Avoid serverless for long-running jobs, persistent connections, heavy stateful processing and workloads that need predictable single-digit-millisecond latency.
What serverless actually means
There are still servers. The difference is who manages them and how you are billed. In a serverless model:
- You deploy units of code, typically functions (AWS Lambda, Azure Functions, Google Cloud Run functions) or containers (AWS Fargate, Azure Container Apps, Google Cloud Run).
- The platform scales automatically from zero to many concurrent instances based on incoming events.
- You pay for usage, usually a per-request charge plus compute time measured in GB-seconds (memory allocated multiplied by execution duration). When nothing runs, you pay little or nothing for compute.
- The provider handles the operating system, runtime patching, capacity and much of the availability engineering.
Serverless also covers managed back-end services that follow the same pay-per-use model: object storage, queues (Amazon SQS, Azure Service Bus, Google Pub/Sub), event buses, serverless databases (DynamoDB, Firestore, Cosmos DB serverless tier, Aurora Serverless) and API gateways.
Functions vs serverless containers
| Aspect | Functions (FaaS) | Serverless containers |
|---|---|---|
| Unit of deployment | Single handler function plus dependencies | Any container image listening on a port |
| Examples | AWS Lambda, Azure Functions, Cloud Run functions | Cloud Run, Azure Container Apps, AWS Fargate (with ECS) |
| Max execution time | Limited (AWS Lambda caps at 15 minutes) | Generally longer, varies by service |
| Framework freedom | Constrained to supported runtimes or custom runtimes | Run any framework, e.g. Express, FastAPI, Spring |
| Scale to zero | Yes | Yes for Cloud Run and Container Apps; Fargate tasks typically keep running |
| Best for | Event handlers, glue code, webhooks | Web APIs and apps you want portable |
How a serverless request flows
Here is a typical flow for an M-Pesa STK Push payment confirmation using AWS services. The same shape applies on Azure or Google Cloud with equivalent products.
Customer phone (M-Pesa)
|
v
Safaricom Daraja API --- HTTPS POST callback ---> API Gateway (HTTPS endpoint)
|
v
Lambda: mpesaCallback
| validate payload
| write to DynamoDB (payments table)
| publish event to SQS
|
v
Lambda: fulfilOrder (SQS trigger)
| update order status
| send SMS / email receipt
Splitting the callback receiver from fulfilment matters. Daraja expects a quick response to its callback, so the receiver should validate, persist and acknowledge, then hand off slower work to a queue.
Whether in the cloud or on premise, workloads still run on physical racks like these.
A small working example
The following Node.js Lambda handler receives a Daraja STK Push callback via API Gateway (HTTP API, payload format 2.0), stores the result in DynamoDB and enqueues fulfilment. It uses the AWS SDK for JavaScript v3, which is bundled with the Node.js Lambda runtimes.
// mpesaCallback.mjs (Node.js 20.x or later Lambda runtime)
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";
// Clients are created outside the handler so warm invocations reuse them.
const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const sqs = new SQSClient({});
const TABLE = process.env.PAYMENTS_TABLE;
const QUEUE_URL = process.env.FULFIL_QUEUE_URL;
function metadataToObject(items = []) {
// CallbackMetadata.Item is an array of { Name, Value } pairs.
return Object.fromEntries(items.map((i) => [i.Name, i.Value]));
}
export const handler = async (event) => {
let body;
try {
body = JSON.parse(event.body ?? "{}");
} catch {
return { statusCode: 400, body: "Invalid JSON" };
}
const cb = body?.Body?.stkCallback;
if (!cb?.CheckoutRequestID) {
return { statusCode: 400, body: "Missing stkCallback" };
}
const meta = metadataToObject(cb.CallbackMetadata?.Item);
const record = {
checkoutRequestId: cb.CheckoutRequestID,
merchantRequestId: cb.MerchantRequestID,
resultCode: cb.ResultCode,
resultDesc: cb.ResultDesc,
amount: meta.Amount ?? null,
receipt: meta.MpesaReceiptNumber ?? null,
phone: meta.PhoneNumber ? String(meta.PhoneNumber) : null,
receivedAt: new Date().toISOString(),
};
// Conditional write makes the handler idempotent if Daraja retries.
try {
await ddb.send(
new PutCommand({
TableName: TABLE,
Item: record,
ConditionExpression: "attribute_not_exists(checkoutRequestId)",
})
);
} catch (err) {
if (err.name !== "ConditionalCheckFailedException") throw err;
return { statusCode: 200, body: JSON.stringify({ ResultCode: 0, ResultDesc: "Duplicate ignored" }) };
}
if (record.resultCode === 0) {
await sqs.send(
new SendMessageCommand({
QueueUrl: QUEUE_URL,
MessageBody: JSON.stringify(record),
})
);
}
return {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ResultCode: 0, ResultDesc: "Accepted" }),
};
};
A few production notes:
- Do not trust the callback blindly. Daraja callbacks do not carry a signature you can verify. Confirm high-value payments using the STK Push query or transaction status APIs, and restrict who can reach the endpoint where practical. See the official docs at developer.safaricom.co.ke.
- Idempotency matters. Payment providers may retry. The conditional write above prevents double-processing.
- Use environment variables or a secrets manager for configuration, never hard-coded credentials.
- Set sensible memory and timeout values. A receiver like this needs little memory and should finish in well under a second.
Cold starts explained
When a function has not run recently, or when traffic scales up and the platform needs new instances, it must create an execution environment, load your runtime and code, and run initialisation logic. That first request pays the cold start penalty. Subsequent requests to the same warm instance are fast.
What affects cold start time:
- Runtime. Interpreted runtimes such as Node.js and Python typically start faster than JVM or .NET runtimes without optimisation. AWS offers SnapStart for some runtimes to reduce this; check current runtime support.
- Package size and dependencies. Large bundles and heavy frameworks slow initialisation. Tree-shake and bundle.
- Initialisation work. Opening database connections, loading large configuration files or ML models at startup all add time.
- VPC networking. Attaching functions to private networks used to add significant cold start time on AWS; this improved substantially, but complex networking can still add overhead.
Mitigations:
- Keep functions small and dependencies lean.
- Do expensive setup once, outside the handler, so warm invocations reuse it.
- Use provisioned concurrency (AWS Lambda), premium or flex plans with always-ready instances (Azure Functions) or minimum instances (Cloud Run) for latency-sensitive paths. These cost money even when idle, which reduces the pay-per-use benefit.
- Push latency-tolerant work onto queues so that cold starts happen off the user's critical path.
For users on mobile networks in East Africa, a few hundred milliseconds of cold start is often smaller than last-mile variability. For a checkout API, though, it adds up. Measure your p95 and p99 latency, not the average.
The cost model
Serverless pricing has three main components:
- Requests: a small charge per million invocations.
- Compute duration: billed in GB-seconds (or vCPU-seconds and GiB-seconds for container platforms).
- Supporting services: API Gateway requests, data transfer, logs, queues and databases. These often exceed the function cost itself.
AWS Lambda, for example, includes a monthly free tier of one million requests and 400,000 GB-seconds at the time of writing. For a small business processing a few thousand M-Pesa callbacks a month, the function cost is effectively negligible. Check the current pricing pages, because rates differ by region and architecture (Arm-based Graviton functions are priced lower than x86 on AWS).
Where serverless gets expensive
The cost curve flips at sustained high throughput. A function that runs constantly at high concurrency can cost more than the equivalent always-on container or VM. Logging is another trap: verbose logs from millions of invocations can produce a larger bill than the compute. To find your crossover point:
- Estimate monthly invocations, average duration and memory size.
- Price the function, gateway, logging and data transfer in the provider calculator.
- Price the same workload on a small container cluster or VM pair with a load balancer.
- Remember to include the engineering time you save on patching and scaling. For a small team, that is real money.
Because hyperscalers bill in USD, keep an FX buffer in your budget. Serverless spend also fluctuates with traffic, so set budget alerts.
Cloud regions and edge locations bring compute closer to users.
When not to use serverless
Use this checklist. If you answer yes to two or more, consider containers or VMs instead.
- Does the job routinely run longer than the platform's maximum execution time (15 minutes on AWS Lambda)?
- Do you need persistent connections, such as long-lived WebSockets managed in-process, or a stateful game server?
- Is traffic high and steady, 24 hours a day, so you rarely benefit from scaling to zero?
- Do you need predictable, very low latency on every request with no tolerance for cold starts?
- Does the workload need GPUs or specialised hardware not offered by the serverless platform?
- Do you open many database connections that could exhaust a relational database's connection limit? (Connection proxies such as Amazon RDS Proxy help, but add cost.)
- Are you subject to data residency rules that the serverless service cannot satisfy in your chosen region?
- Does your team lack observability tooling to trace requests across many small functions?
Serverless in an East African context
- Region choice. Not every serverless feature is available in African regions on day one. Check service availability in af-south-1, South Africa North or africa-south1 before designing. Our AWS vs Azure vs Google Cloud comparison covers the region landscape.
- Payment integrations. M-Pesa, Airtel Money and card gateway webhooks are natural fits for serverless receivers because they are event-driven and bursty around paydays and promotions.
- Data protection. If functions process personal data such as phone numbers and names, the Kenya Data Protection Act 2019 applies. Minimise what you store, encrypt at rest, and document cross-border transfers.
- Skills. Serverless shifts work from server administration to distributed systems design and observability. Invest in tracing, structured logging and infrastructure-as-code (AWS SAM, Terraform, Bicep) early.
Common mistakes
- Treating functions like a monolith. Putting an entire web framework into one function produces slow cold starts and makes scaling coarse.
- Synchronous chains. Function A calling B calling C over HTTP multiplies latency and failure points. Use queues and events.
- No idempotency. Event sources retry. Every handler that changes state should be safe to run twice.
- Unbounded concurrency hitting a database. A traffic spike scales functions instantly; your PostgreSQL instance does not. Set reserved concurrency limits or use a queue as a buffer.
- Ignoring log costs. Set log retention periods and avoid logging full payloads, which may also contain personal data.
- Console-only deployments. Manual changes drift. Use infrastructure-as-code from the first function.
FAQ
Is serverless cheaper than running a VM?
For intermittent or low-volume workloads, almost always. For high, steady traffic, often not. Model your expected volume and include supporting services like API gateways and logging.
Do serverless functions work with M-Pesa Daraja?
Yes. Daraja callbacks are HTTPS POST requests, which map cleanly to a function behind an API gateway. Keep the handler fast, idempotent and verify important transactions using Daraja's query APIs.
What is a cold start and should I worry about it?
A cold start is the extra delay when the platform creates a new execution environment. It matters for user-facing, latency-sensitive endpoints. Mitigate with lean packages, faster runtimes and provisioned or minimum instances.
Can I avoid vendor lock-in with serverless?
Partly. Serverless containers such as Cloud Run or Azure Container Apps are more portable than functions tied to provider-specific event formats. Keeping business logic in plain modules, separate from the handler, also eases migration.
Is serverless secure?
The provider secures the underlying infrastructure, but you remain responsible for code, dependencies, permissions and data. Apply least-privilege IAM roles per function and follow OWASP guidance for APIs.
How TechBytes can help
We design and build event-driven back ends, including M-Pesa and card payment callbacks, with infrastructure-as-code, idempotent handlers and proper monitoring. We also model serverless versus container costs for your actual traffic so you know where the crossover sits. Talk to our software development team about a new build, or see cloud computing benefits for small businesses if you are earlier in your cloud journey.
