Skip to content

⭐ feat(infra): Migrate to serverless Lambda architecture#291

Merged
wanjohiryan merged 2 commits intomainfrom
fix/auth
Jun 9, 2025
Merged

⭐ feat(infra): Migrate to serverless Lambda architecture#291
wanjohiryan merged 2 commits intomainfrom
fix/auth

Conversation

@wanjohiryan
Copy link
Member

@wanjohiryan wanjohiryan commented Jun 9, 2025

Description

Summary by CodeRabbit

  • New Features

    • Introduced serverless API and authentication endpoints, improving scalability and reliability.
    • Added rate limiting to the API, providing protection against excessive requests and returning custom error responses.
  • Improvements

    • Simplified infrastructure for both API and authentication, reducing complexity and improving maintainability.
    • Updated resource allocations for backend services to optimize performance and cost.
  • Bug Fixes

    • Removed unused scripts and configuration, resulting in a cleaner development environment.
  • Other

    • Updated type declarations to reflect new infrastructure changes.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 9, 2025

Walkthrough

The changes migrate the API and authentication infrastructure from container-based services to serverless AWS Lambda functions, update type declarations to reflect this shift, and add AWS WAF rate limiting for the API. Related scripts and exports are updated or removed, and resource allocations for supporting services are simplified.

Changes

File(s) Change Summary
infra/api.ts, infra/auth.ts Migrated API and Auth from sst.aws.Service to sst.aws.Function and sst.aws.Auth; updated routing, removed service-specific configs, added WAF to API.
infra/realtime.ts Removed dependency on auth in the authorizer's linked resources.
infra/zero.ts Simplified resource allocations for services, removed environment-based conditional logic.
packages/functions/package.json Removed development scripts for API and Auth.
packages/functions/src/api/index.ts Refactored to export a Lambda handler, removed default export/server config, dropped /realtime route.
packages/functions/src/auth/index.ts Refactored to export a Lambda handler, removed memory storage and server config.
sst-env.d.ts Updated resource type declarations for API and Auth, added ApiFn resource, removed obsolete properties.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CloudFront
    participant WAF
    participant LambdaAPI
    participant LambdaAuth

    Client->>CloudFront: HTTP Request (API/Auth)
    CloudFront->>WAF: Forward request
    WAF-->>CloudFront: Allow or Block (rate limit)
    alt API Route
        CloudFront->>LambdaAPI: Invoke Lambda handler
        LambdaAPI-->>CloudFront: Response
    else Auth Route
        CloudFront->>LambdaAuth: Invoke Lambda handler
        LambdaAuth-->>CloudFront: Response
    end
    CloudFront-->>Client: Return response
Loading

Poem

In the warren of code, the servers once spun,
But now, with a hop, we've gone Lambda—what fun!
WAF guards the gate, rate limits in place,
The scripts have all vanished, there's less to chase.
With simpler exports and cloud in the sky,
The rabbits rejoice as the functions now fly!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@wanjohiryan wanjohiryan self-assigned this Jun 9, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
infra/realtime.ts (1)

1-1: Remove commented import or clarify the intention.

The auth import is commented out rather than removed entirely. If auth is no longer needed, remove the line completely. If there's uncertainty, please clarify the intention.

-// import { auth } from "./auth";
infra/api.ts (1)

8-26: Lambda function configuration is well-structured.

The function setup with VPC integration and linked resources is appropriate. However, consider enabling streaming in development for better dev/prod parity.

-    streaming: !$dev,
+    streaming: true, // Enable for dev/prod parity
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e82eff and 9bf12f1.

📒 Files selected for processing (8)
  • infra/api.ts (2 hunks)
  • infra/auth.ts (1 hunks)
  • infra/realtime.ts (1 hunks)
  • infra/zero.ts (2 hunks)
  • packages/functions/package.json (0 hunks)
  • packages/functions/src/api/index.ts (3 hunks)
  • packages/functions/src/auth/index.ts (2 hunks)
  • sst-env.d.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/functions/package.json
🧰 Additional context used
🧬 Code Graph Analysis (2)
infra/api.ts (1)
infra/dns.ts (1)
  • domain (1-5)
infra/realtime.ts (1)
infra/postgres.ts (1)
  • postgres (3-36)
🔇 Additional comments (16)
infra/zero.ts (3)

8-8: LGTM: Connection string explicitly includes port.

The explicit port inclusion in the connection string template improves clarity and reduces potential connection issues.


44-46: Verify the resource reduction impact on replication performance.

The resource allocation has been significantly reduced to 0.5 vCPU and 1 GB memory with spot capacity. For a replication manager handling real-time data synchronization, this reduction could impact performance and availability.

Consider the following concerns:

  • Spot instances can be terminated, potentially disrupting replication
  • Reduced CPU/memory may cause bottlenecks during high-load periods
  • Zero replication typically requires consistent performance for data consistency

Please verify that these reduced resources are sufficient for your replication workload, especially during peak usage periods.


128-130: Verify the resource reduction impact on zero service performance.

Similar to the replication manager, the main zero service now uses significantly reduced resources (0.5 vCPU, 1 GB memory, spot capacity). This could impact the performance of the zero synchronization service.

Please ensure these resource constraints are adequate for your zero service workload, particularly given the service handles real-time synchronization with up to 4 instances in the scaling configuration.

infra/realtime.ts (1)

6-6:

Details

✅ Verification successful

Verify realtime authorization still functions without auth link.

The auth module has been removed from the authorizer's link array, leaving only postgres. Please ensure that the realtime authorizer can still properly authenticate users without the auth service dependency.


🏁 Script executed:

#!/bin/bash
# Description: Check how the realtime authorizer handles authentication without the auth link

# Find the authorizer handler implementation
ast-grep --pattern 'export $_ handler($_) {
  $$$
}'

# Look for auth-related imports and usage in the authorizer
rg -A 10 "authorizer\.handler" 
rg -A 5 "auth.*import\|import.*auth"

Length of output: 259


🏁 Script executed:

#!/bin/bash
set -e

# Locate authorizer implementation files
echo "Authorizer files in packages/functions/src/realtime/:"
find packages/functions/src/realtime -maxdepth 1 -type f -print

# Print the first 50 lines of each authorizer file to inspect imports and logic
for file in packages/functions/src/realtime/authorizer*; do
  echo -e "\n==== $file ===="
  sed -n '1,50p' "$file"
done

# Search for any auth-related imports within those files
echo -e "\nAuth-related import lines:"
rg -n "import.*auth" packages/functions/src/realtime/authorizer*

# Search for any usage of 'auth' or 'verify' keywords in those files
echo -e "\nAuth-related usage lines:"
rg -n "auth|verify" packages/functions/src/realtime/authorizer*

Length of output: 2271


No changes needed: auth link removal is safe

We’ve confirmed that the realtime authorizer in packages/functions/src/realtime/authorizer.ts:

  • Imports and uses Resource.Auth.url at build time (issuer is a static string, not injected via environment).
  • Calls client.verify(subjects, token) over HTTPS to fetch JWKs and validate tokens.
  • Requires no env vars or direct VPC link to the Auth construct.

Linking only [postgres] still gives the function VPC/NAT for outbound requests, so dropping the Auth link does not break authentication.

packages/functions/src/auth/index.ts (2)

4-4: LGTM: Proper import for Lambda handler conversion.

The addition of the handle import from hono/aws-lambda is correct for converting the service to a Lambda function.


159-159: LGTM: Clean conversion to Lambda handler.

The export change from a server configuration object to a single Lambda handler using handle(app) is the correct approach for migrating from a containerized service to AWS Lambda. This properly wraps the Hono app for Lambda execution.

sst-env.d.ts (3)

10-12: LGTM: Type definitions align with Router migration.

The Api resource type change from sst.aws.Service to sst.aws.Router with the removal of the service property correctly reflects the infrastructure migration to a router-based API.


13-17: LGTM: New function resource type definition.

The addition of the ApiFn resource with sst.aws.Function type properly represents the new serverless function replacing the previous service-based API.


19-19: LGTM: Auth type updated for managed service.

The Auth resource type change from sst.aws.Service to sst.aws.Auth correctly reflects the migration to a managed authentication service.

packages/functions/src/api/index.ts (3)

2-2: Lambda handler imports look good.

The Hono framework integration with AWS Lambda handlers is properly set up.

Also applies to: 13-13


30-30: Realtime route removal aligns with Lambda limitations.

The removal of the /realtime route is appropriate since AWS Lambda doesn't support persistent WebSocket connections directly. If realtime functionality is still needed, consider using AWS API Gateway WebSocket APIs or a separate service.


96-98: Handler export configured correctly for Lambda.

The conditional use of streamHandle vs handle based on SST_LIVE is a good approach. Just ensure that the behavior differences between streaming and non-streaming modes are well-tested.

infra/auth.ts (2)

7-32: Auth service migration to managed construct looks good.

The migration from containerized service to sst.aws.Auth significantly simplifies the infrastructure while maintaining all necessary functionality. The VPC integration and linked resources are properly configured.


25-25:

Details

✅ Verification successful

Verify the auth handler exists at the specified path.

Ensure that the handler file exists and exports a proper Lambda handler function.


🏁 Script executed:

#!/bin/bash
# Description: Verify the auth handler file exists and has proper exports

# Check if the handler file exists
fd -t f "index.ts" packages/functions/src/auth/

# Verify the handler export
ast-grep --pattern 'export const handler = $_' packages/functions/src/auth/

Length of output: 368


Auth handler path and export confirmed

The file packages/functions/src/auth/index.ts exists and correctly exports handler (export const handler = handle(app);). No further action is needed.

infra/api.ts (2)

28-29: WAF configuration and CloudFront integration look correct.

The WAF is properly configured with CloudFront scope and custom rate limit response. The use of us-east-1 provider is required for CloudFront WAF integration.

Also applies to: 30-89


91-111: Router configuration with WAF attachment is properly implemented.

The transform hook correctly attaches the WAF to the CloudFront distribution. This ensures API protection at the edge.

@wanjohiryan
Copy link
Member Author

@coderabbitai give me 5 suitable PR titles for this PR, use our title format please

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 9, 2025

Tip

For best results, initiate chat on the files or code changes.

@wanjohiryan Here are 5 suitable PR titles following your format:

  1. 🧹 chore(infra): Move to AWS Lambda
  2. 🚀 feat(infra): Migrate to serverless Lambda architecture
  3. ♻️ refactor(infra): Replace container services with Lambda functions
  4. ⚡ perf(infra): Transition API and Auth to AWS Lambda
  5. 🔧 chore(infra): Modernize infrastructure with Lambda and WAF

Each title captures a different aspect of your changes:

  • Option 1: Your current title (clean and concise)
  • Option 2: Emphasizes the serverless architecture transformation
  • Option 3: Highlights the container-to-Lambda migration
  • Option 4: Focuses on performance benefits of the Lambda transition
  • Option 5: Mentions both Lambda migration and WAF addition

All follow your [emoji] [type]([scope]): [description] format with "infra" as the scope.

@wanjohiryan wanjohiryan changed the title 🧹 chore(infra): Move to AWS Lambda ⭐ feat(infra): Migrate to serverless Lambda architecture Jun 9, 2025
@wanjohiryan wanjohiryan merged commit be85594 into main Jun 9, 2025
1 check passed
@wanjohiryan wanjohiryan deleted the fix/auth branch June 9, 2025 07:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant