AWS Builder Center

AWS Lambda Web Functions Through the AWS Console - Part 2

AWS Lambda Web Functions Through the AWS Console - Part 2

Dev @ Vertex Macro

Step 7: Create Cognito authentication for the small user group

Create the user pool

  1. Open Amazon Cognito.
  1. Choose Create user pool.
  1. Choose Traditional web application or the closest interactive browser application type shown by the console.
  1. Name the application  fsi-trading-desk-portal .
  1. Name the user pool  fsi-trading-desk-users .
  1. Use email as the sign-in identifier unless the firm's identity architecture dictates another identifier.
  1. Require MFA. For a financial-services production environment, prefer TOTP or enterprise federation rather than SMS alone.
  1. Set a strong password policy.
  1. Disable self-registration. Users must be provisioned by an administrator or federated from the corporate identity provider.
  1. Configure a custom domain or Cognito-hosted domain for testing.
  1. Set callback URL to the future CloudFront URL and use a temporary localhost callback only for controlled development.
  1. Use authorization code grant with PKCE for the browser application.
  1. Request only required scopes such as  openid ,  email , and  profile .
  1. Create the user pool and application client.
  1. Record the user pool ID and application client ID.

Create the desk authorization group

  1. In the user pool, open Groups.
  1. Create group  TradingDeskReaders .
  1. Add only approved users.
  1. Create a separate group such as  TradingDeskAdmins  if write or administration APIs will be added. Never infer write privilege from a reader group.

Update the Web Function revision

A Web Function revision is immutable. To add Cognito environment variables:
  1. Open the Web Function.
  1. Choose Create revision.
  1. Reuse the same versioned S3 code object.
  1. Set:
  •  COGNITO_USER_POOL_ID=<your pool ID> 
  •  COGNITO_APP_CLIENT_ID=<your app client ID> 
  •  TABLE_NAME=FundMetrics 
  •  ALLOWED_ORIGIN=https://<CloudFront-domain>  after Step 9
  1. Select the same execution role and KMS key.
  1. Create the revision and wait for Active.
  1. If automatic deployment is disabled, update the endpoint to route 100% to the new revision.
  1. Keep the previous revision available for rollback.



Step 8: Test the authenticated API

After signing in, obtain a Cognito access token through authorization code flow with PKCE. Do not place an ID token or access token in a URL.
export ACCESS_TOKEN='REDACTED'
export API_BASE='https://REPLACE_WITH_ENDPOINT_DOMAIN'

curl -sS \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
"${API_BASE}/api/v1/funds/DEMO01/overview"
Expected shape:
{
"fundId": "DEMO01",
"fundName": "Synthetic Market Neutral Fund",
"currency": "USD",
"managementMetrics": {
"topHoldingsEndpoint": "/api/v1/funds/DEMO01/holdings",
"largestTradesEndpoint": "/api/v1/funds/DEMO01/trades",
"portfolioStructureEndpoint": "/api/v1/funds/DEMO01/structure"
},
"performance": {
"nav": 125000000,
"regulatoryAum": 155000000,
"fundReturnYtd": 0.084,
"sp500ReturnYtd": 0.126,
"alphaYtd": -0.042,
"trackingError": 0.071
},
"provenance": {
"positionsAsOf": "2026-10-29T08:00:00Z",
"marketDataAsOf": "2026-10-29T08:00:00Z",
"regulatoryDataAsOf": "2026-09-30",
"dataQualityStatus": "SYNTHETIC",
"calculatedAt": "2026-10-29T08:31:00Z"
}
}
Test all negative cases:
  • no token returns  401 ;
  • expired or wrong-client token returns  401 ;
  • valid user outside  TradingDeskReaders  returns  403 ;
  • unknown fund returns  404 ;
  • invalid fund ID returns  400 ;
  • DynamoDB or KMS denial returns  500  without exposing implementation details.



Step 9: Create the private S3 landing page

Create the website bucket

  1. Open S3 and create bucket  fsi-trading-desk-portal-123456789012 .
  1. Keep Block all public access enabled.
  1. Enable versioning.
  1. Enable default SSE-KMS encryption.
  1. Do not enable S3 static website hosting for this secure pattern. CloudFront will use the S3 REST origin with OAC.

Sample  index.html 

This minimal page intentionally leaves authentication integration to an approved OIDC/PKCE library or corporate identity component. Do not hand-build cryptographic PKCE or store long-lived refresh tokens in  localStorage  without security review.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; connect-src 'self' https://REPLACE_WITH_API_DOMAIN; object-src 'none'; base-uri 'none'; frame-ancestors 'none'">
<title>Trading Desk Fund Review</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; color: #17202a; }
.notice { padding: 1rem; background: #fff4ce; border-left: 4px solid #c78b00; }
.grid { display: grid; grid-template-columns: repeat(auto-fit,minmax(220px,1fr)); gap: 1rem; margin-top: 1rem; }
.card { border: 1px solid #d5d8dc; border-radius: 8px; padding: 1rem; }
button { padding: .7rem 1rem; }
</style>
</head>
<body>
<h1>Trading Desk Fund Review</h1>
<p class="notice">Confidential. Synthetic demonstration until data validation status is APPROVED.</p>
<button id="load" type="button">Load approved demo fund</button>
<p id="status" role="status"></p>
<section id="metrics" class="grid" aria-live="polite"></section>
<script>
const apiBase = 'https://REPLACE_WITH_API_DOMAIN';
const accessToken = ''; // Obtain using approved Cognito OIDC authorization-code + PKCE integration.
document.getElementById('load').addEventListener('click', async () => {
const status = document.getElementById('status');
const metrics = document.getElementById('metrics');
if (!accessToken) {
status.textContent = 'Sign in through the approved Cognito flow before loading fund data.';
return;
}
status.textContent = 'Loading...';
metrics.replaceChildren();
try {
const response = await fetch(`${apiBase}/api/v1/funds/DEMO01/overview`, {
headers: { Authorization: `Bearer ${accessToken}` },
cache: 'no-store'
});
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
const data = await response.json();
const values = [
['NAV', data.performance.nav],
['Regulatory AUM', data.performance.regulatoryAum],
['Fund return YTD', data.performance.fundReturnYtd],
['S&P 500 return YTD', data.performance.sp500ReturnYtd],
['Alpha YTD', data.performance.alphaYtd],
['Tracking error', data.performance.trackingError]
];
for (const [label, value] of values) {
const card = document.createElement('article');
card.className = 'card';
const h2 = document.createElement('h2');
h2.textContent = label;
const p = document.createElement('p');
p.textContent = String(value);
card.append(h2, p);
metrics.append(card);
}
status.textContent = `Data calculated at ${data.provenance.calculatedAt}`;
} catch (error) {
status.textContent = error.message;
}
});
</script>
</body>
</html>
Upload  index.html  through the S3 console.



Step 10: Create CloudFront for the landing page

  1. Open CloudFront.
  1. Choose Create distribution.
  1. Select the private S3 bucket as the origin.
  1. Create an Origin Access Control (OAC) and allow CloudFront to update the S3 bucket policy.
  1. Set Viewer protocol policy to Redirect HTTP to HTTPS.
  1. Allow only  GET ,  HEAD , and  OPTIONS  for the static site behavior.
  1. Set the default root object to  index.html .
  1. Add a response headers policy with:
  • Strict-Transport-Security;
  • Content-Security-Policy adjusted for the Cognito and API domains;
  • X-Content-Type-Options  nosniff ;
  • Referrer-Policy;
  • frame protection through CSP  frame-ancestors 'none' .
  1. For a custom domain, request an ACM certificate in  us-east-1 , validate it, and attach it to the distribution.
  1. Create or update Route 53 records if Route 53 manages the domain.
  1. Wait for distribution deployment.
  1. Update the Cognito callback and sign-out URLs to the CloudFront/custom-domain URLs.
  1. Create a new Web Function revision with  ALLOWED_ORIGIN  set to the exact HTTPS portal origin.
AWS recommends S3 plus CloudFront with OAC for a secure static website. This keeps the bucket private and serves the site through HTTPS. See  Secure static website with CloudFront .

API behind the same CloudFront distribution

For a clean same-origin design, add the Lambda Web Function endpoint as a second CloudFront origin and route  /api/*  to it. Confirm that Lambda Web Function endpoints are supported by the selected CloudFront origin configuration in your Region and account. If OAC support is not available for Web Function endpoints, keep Cognito validation mandatory and restrict access using WAF, rate limits, and a controlled partner network path.
Do not confuse the new Lambda Web Function endpoint with a classic Lambda Function URL. AWS documents CloudFront OAC for classic Lambda Function URL origins separately:  Restrict access to a Lambda function URL origin .



Step 11: Add AWS WAF controls

  1. Open AWS WAF.
  1. Create a web ACL for CloudFront scope.
  1. Associate it with the CloudFront distribution.
  1. Start managed rule groups in count mode, inspect results, then move approved rules to block mode.
  1. Add a rate-based rule. Choose a threshold based on expected desk traffic and load tests rather than copying an arbitrary Internet-scale value.
  1. Add an allow list for known office egress IP ranges only if partners have stable IP addresses. Do not use IP allow lists as the only identity control.
  1. Enable WAF logging to the approved destination and retention tier.
AWS WAF can inspect requests by IP address and request components, apply rate controls, and block or challenge requests. See  AWS WAF documentation  and  Use AWS WAF protections with CloudFront .



Step 12: Configure monitoring, audit, and alarms

CloudWatch logs

  1. Open CloudWatch Logs.
  1. Locate the Web Function log group after the first request.
  1. Set the retention period required by the firm's policy. Do not retain confidential payloads indefinitely.
  1. Encrypt the log group with the approved KMS key if required.
  1. Create metric filters for:
  •  auth_failure ;
  •  api_error ;
  • unusually high  403  and  429  activity;
  • unsuccessful deployment or endpoint states.
Never log access tokens, full customer identifiers, full order payloads, credentials, or raw confidential portfolio data.

CloudWatch alarms

Create alarms for:
  • 5xx error rate above the desk's agreed threshold;
  • high p95/p99 latency;
  • elevated throttling or rejected requests;
  • DynamoDB throttling or system errors;
  • WAF blocked request spikes;
  • missing successful health checks;
  • abnormal cost or request volume through AWS Budgets and Cost Anomaly Detection.

CloudTrail

Confirm CloudTrail records control-plane activity for:
  • Web Function creation and revision changes;
  • endpoint routing changes;
  • IAM policy or role changes;
  • S3 object version deletion;
  • KMS key policy changes;
  • Cognito user and group administration;
  • WAF and CloudFront changes.
Send trails to a separate central logging account with object lock or equivalent retention controls where required.



Step 13: Calculate the financial metrics correctly

Top holdings and concentration

For position  i :
weight_i = market_value_i / sum(abs(market_value_all_positions))
Top10Exposure = sum(weight_i for the ten largest absolute positions)
HHI = sum(weight_i ^ 2)
State whether gross, net, or long-only market value is used. For long/short portfolios, a net denominator can create misleading weights near zero. Validate the denominator with risk management.

Largest trades

Do not infer a trade from a single Form 13F comparison without qualification. A quarter-to-quarter position change may reflect purchases, sales, corporate actions, transfers, security identifier changes, options treatment, or valuation movement.
Useful fields:
position_delta = current_quantity - prior_quantity
notional_delta = current_market_value - prior_market_value
turnover_contribution = abs(purchases + sales) / average_nav
Label “block trade” only when it is sourced from an approved execution or order-management record, not merely a large change in a filing.

Performance versus S&P 500

For the same approved period and currency:
relative_return = fund_return - benchmark_return
beta = covariance(fund_returns, benchmark_returns) / variance(benchmark_returns)
alpha = fund_return - [risk_free_rate + beta * (benchmark_return - risk_free_rate)]
tracking_error = annualized_stddev(fund_return_series - benchmark_return_series)
information_ratio = annualized_active_return / tracking_error
Document:
  • gross or net return;
  • fee treatment;
  • dividend treatment;
  • benchmark variant, such as price return versus total return;
  • annualization method;
  • trading calendar;
  • currency and FX source;
  • stale-price and missing-day policy.

TVPI, IRR, and J-curve

These metrics are generally associated with private capital and should not be mixed into a public-equity hedge fund dashboard without asset-class labels.
TVPI = (Residual Value + Distributions) / Paid-In Capital
IRR is the discount rate that sets the net present value of dated cash flows to zero. Use an approved XIRR implementation and retain the cash-flow snapshot, valuation date, and calculation version.

Regulatory AUM

Treat Form ADV Part 1A RAUM as regulatory data with a filing date and source reference. Keep it distinct from internal NAV and current gross exposure. Store:
  • filing date;
  • SEC file number or approved internal reference;
  • source system;
  • RAUM value and currency;
  • extraction time;
  • validation status;
  • reviewer and approval timestamp.



Deployment promotion and rollback

Web Function revisions are immutable. Use this as a control:
  1. Build and scan a new ZIP.
  1. Upload to a new S3 key and object version.
  1. Create a new Web Function revision.
  1. Wait for  Active .
  1. Run health, authentication, integration, data-quality, and performance tests.
  1. Route a small traffic weight to the new revision if the endpoint supports the required weighted deployment pattern.
  1. Observe errors and latency.
  1. Move 100% to the new revision after approval.
  1. Roll back by routing traffic to the prior healthy revision.
  1. Retain S3 package versions for every active or rollback revision.
Do not enable  Latest revision  auto-deployment on a production endpoint if change approval and segregation of duties are required.



Failure modes and how to diagnose them

  • Symptom: Revision and endpoint show Active, but requests fail Likely cause: Server did not listen on  AWS_LAMBDA_HTTP_ENDPOINT ; entry file not at ZIP root Action: Inspect logs, verify  index.js , host, and port; deploy a new revision
  • Symptom: Revision becomes Failed later Likely cause: Referenced S3 object version deleted or Lambda lost bucket/KMS access Action: Restore policy, create a new revision referencing an available object version, and reroute endpoint
  • Symptom: Browser CORS error Likely cause:  ALLOWED_ORIGIN  differs from portal origin or preflight is blocked Action: Use exact scheme and host; permit  OPTIONS , required headers, and methods
  • Symptom: API returns 401 Likely cause: Wrong token type, issuer, app client, expiry, or missing Bearer prefix Action: Use Cognito access token and verify pool/client settings
  • Symptom: API returns 403 Likely cause: User not in  TradingDeskReaders  Action: Add user through the approved access process and sign in again for refreshed claims
  • Symptom: DynamoDB AccessDenied Likely cause: Execution role policy or KMS permission is incomplete Action: Check exact table ARN, role, key policy, and CloudTrail
  • Symptom: Slow first request Likely cause: Scale-to-zero cold start, dependency size, or synchronous initialization Action: Reduce package size, avoid network work at startup, and test latency objectives
  • Symptom: Incorrect alpha Likely cause: Fund and benchmark returns use different periods, currencies, or total-return conventions Action: Reconcile calendars, FX, fees, dividends, and risk-free-rate assumptions



Cost and capacity approach

This architecture avoids an always-on server, but it is not automatically free. Cost drivers include:
  • Web Function compute and request duration;
  • CloudFront requests and data transfer;
  • S3 storage, requests, KMS operations, and version retention;
  • DynamoDB reads, writes, backups, and global tables if later added;
  • Cognito monthly active users;
  • AWS WAF web ACL, rules, and requests;
  • CloudWatch log ingestion, storage, metrics, and alarms;
  • Secrets Manager secret storage and API calls;
  • Route 53 and ACM-related services where applicable.
Build a cost model from expected requests per trader, response size, execution duration, memory, active users, log volume, retention, and data transfer. Add AWS Budgets and Cost Anomaly Detection before production. Do not rely on a free tier or another cloud provider's free plan.



Official AWS references




Final implementation recommendation

For the first controlled release, use a single  ap-east-1  Home-Region Lambda Web Function endpoint, a private S3 portal behind CloudFront OAC, Cognito with MFA and an administrator-managed  TradingDeskReaders  group, DynamoDB for approved metric snapshots, KMS encryption, WAF controls, and centralized CloudWatch/CloudTrail evidence.
Keep the API read-only until identity, data lineage, timestamp labeling, authorization, market-data licensing, monitoring, rollback, and compliance review have passed. Add trade execution or order-routing capability only as a separate, independently controlled system with stronger transactional, authorization, surveillance, and resiliency requirements.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article