Skip to content

chore: k6 benchmarks#3675

Merged
chronark merged 1 commit intomainfrom
07-29-chore_k6_benchmarks
Jul 29, 2025
Merged

chore: k6 benchmarks#3675
chronark merged 1 commit intomainfrom
07-29-chore_k6_benchmarks

Conversation

@chronark
Copy link
Collaborator

@chronark chronark commented Jul 29, 2025

What does this PR do?

Add k6 load testing scripts for benchmarking v1 and v2 Unkey APIs. The PR includes two benchmark scripts:

  1. ratelimit.js - Tests ratelimiting endpoints with random identifiers
  2. keyverify.js - Tests key verification endpoints

Both scripts compare performance between v1 (api.unkey.dev) and v2 (api.unkey.com) APIs with a 50/50 traffic split.

Fixes # (issue)

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Run the ratelimit benchmark: UNKEY_ROOT_KEY=your_key REGION=us-east k6 cloud ratelimit.js
  • Run the key verification benchmark: UNKEY_ROOT_KEY=your_key KEY=your_test_key k6 cloud keyverify.js
  • Verify metrics are collected in Grafana Cloud under project ID 3788521

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features
    • Introduced new benchmark tools for API load testing, including scripts for rate limiting and key verification endpoints.
    • Added detailed documentation with setup instructions, environment variable usage, and test configuration details.
    • Implemented performance metrics collection and integration with Grafana Cloud for result visualization.

@vercel
Copy link

vercel bot commented Jul 29, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 29, 2025 8:15am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 29, 2025 8:15am

@changeset-bot
Copy link

changeset-bot bot commented Jul 29, 2025

⚠️ No Changeset found

Latest commit: cb7a4d0

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 29, 2025

📝 Walkthrough

Walkthrough

Three new files are introduced in the go/benchmarks directory: a README providing documentation for API benchmarking tools, and two k6 load testing scripts (ratelimit.js and keyverify.js) for benchmarking ratelimiting and key verification endpoints. The scripts implement randomized API version selection, custom metrics, and enforce latency and success thresholds.

Changes

Cohort / File(s) Change Summary
Benchmark Documentation
go/benchmarks/README.md
Added a README documenting the purpose, usage, setup, configuration, and metrics of the API benchmark tools. Describes the two k6 scripts, required environment variables, traffic split logic, test parameters, and integration with Grafana Cloud for metrics visualization.
Key Verification Benchmark Script
go/benchmarks/keyverify.js
Introduced a k6 load testing script for benchmarking key verification API endpoints. Implements randomized POST requests to v1 and v2 endpoints, uses environment variables for configuration, sets HTTP headers, checks response status, and records request latency in a custom metric. Defines k6 test options for cloud execution, load stages, and performance thresholds.
Rate Limiting Benchmark Script
go/benchmarks/ratelimit.js
Added a k6 benchmark script for rate limiting APIs. Randomly selects user identifiers and API versions, sends POST requests to the ratelimit endpoints, checks for 200 status, and records latency in a custom metric. Configures test options for cloud execution, load stages, and performance thresholds. Uses environment variables for authorization and region configuration.

Sequence Diagram(s)

sequenceDiagram
    participant k6_Script as k6 Script (ratelimit.js / keyverify.js)
    participant API_v1 as API v1 Endpoint
    participant API_v2 as API v2 Endpoint

    loop For each test iteration
        k6_Script->>k6_Script: Randomly select API version (v1 or v2)
        alt v1 selected
            k6_Script->>API_v1: POST request with payload and headers
        else v2 selected
            k6_Script->>API_v2: POST request with payload and headers
        end
        API_v1-->>k6_Script: Response (status, latency)
        API_v2-->>k6_Script: Response (status, latency)
        k6_Script->>k6_Script: Record latency metric and check status
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Suggested reviewers

  • perkinsjr
  • mcstepp
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 07-29-chore_k6_benchmarks

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 generate unit tests to generate unit tests for 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.

Copy link
Collaborator Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@github-actions
Copy link
Contributor

Thank you for following the naming conventions for pull request titles! 🙏

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: 9

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f0c84e and cb7a4d0.

📒 Files selected for processing (3)
  • go/benchmarks/README.md (1 hunks)
  • go/benchmarks/keyverify.js (1 hunks)
  • go/benchmarks/ratelimit.js (1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: chronark
PR: unkeyed/unkey#3474
File: go/apps/api/routes/v2_keys_verify_key/200_test.go:380-380
Timestamp: 2025-07-14T08:15:56.747Z
Learning: In the Unkey codebase, there is a mechanism to set the server's time via a header for test control, which helps make ratelimit tests deterministic instead of time-dependent. This is useful for preventing flaky tests where the second request might hit a new ratelimit window.
go/benchmarks/README.md (2)

Learnt from: chronark
PR: #3474
File: go/apps/api/routes/v2_keys_verify_key/200_test.go:380-380
Timestamp: 2025-07-14T08:15:56.747Z
Learning: In the Unkey codebase, there is a mechanism to set the server's time via a header for test control, which helps make ratelimit tests deterministic instead of time-dependent. This is useful for preventing flaky tests where the second request might hit a new ratelimit window.

Learnt from: CR
PR: unkeyed/unkey#0
File: go/deploy/CLAUDE.md:0-0
Timestamp: 2025-07-21T18:05:58.236Z
Learning: Applies to go/deploy/**/*.{go,js,ts,tsx,py,sh,md,txt,json,yaml,yml,ini,env,conf,html,css,scss,xml,c,h,cpp,java,rb,rs,php,pl,sql} : Make sure to add relevant anchor comments whenever a file or piece of code is too complex, very important, confusing, or could have a bug.

go/benchmarks/keyverify.js (6)

Learnt from: chronark
PR: #3474
File: go/apps/api/routes/v2_keys_verify_key/200_test.go:380-380
Timestamp: 2025-07-14T08:15:56.747Z
Learning: In the Unkey codebase, there is a mechanism to set the server's time via a header for test control, which helps make ratelimit tests deterministic instead of time-dependent. This is useful for preventing flaky tests where the second request might hit a new ratelimit window.

Learnt from: MichaelUnkey
PR: #2114
File: apps/api/src/routes/v1_keys_updateKey.error.test.ts:0-0
Timestamp: 2024-09-27T15:20:05.475Z
Learning: In the v1/keys.updateKey endpoint, the server validates the refill configuration before checking if the key exists. Therefore, tests can assert validation errors without needing to create the key first.

Learnt from: Flo4604
PR: #2955
File: go/apps/api/routes/v2_identities_create_identity/handler.go:162-202
Timestamp: 2025-03-19T09:25:59.751Z
Learning: In the Unkey codebase, input validation for API endpoints is primarily handled through OpenAPI schema validation, which occurs before requests reach the handler code. For example, in the identities.createIdentity endpoint, minimum values for ratelimit duration and limit are defined in the OpenAPI schema rather than duplicating these checks in the handler.

Learnt from: ogzhanolguncu
PR: #3242
File: apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/components/table/hooks/use-logs-query.ts:228-231
Timestamp: 2025-05-15T16:21:50.911Z
Learning: The codebase for Unkey allows the use of modern JavaScript features like Array.prototype.toSorted() even though they may not be supported in all browsers.

Learnt from: ogzhanolguncu
PR: #3292
File: apps/dashboard/lib/trpc/routers/key/create.ts:11-14
Timestamp: 2025-06-02T11:09:58.791Z
Learning: In the unkey codebase, TypeScript and the env() function implementation already provide sufficient validation for environment variables, so additional runtime error handling for missing env vars is not needed.

Learnt from: chronark
PR: #3617
File: go/apps/api/openapi/openapi.yaml:3309-3312
Timestamp: 2025-07-16T17:51:57.297Z
Learning: In the Unkey API OpenAPI schema, the permissions query regex for the verifyKey endpoint intentionally allows all whitespace characters (including tabs and newlines) via \s. Do not flag this as an error in future reviews.

go/benchmarks/ratelimit.js (3)

Learnt from: chronark
PR: #2544
File: apps/api/src/pkg/env.ts:4-6
Timestamp: 2024-10-23T12:05:31.121Z
Learning: The cloudflareRatelimiter type definition in apps/api/src/pkg/env.ts should not have its interface changed; it should keep the limit method returning Promise<{ success: boolean }> without additional error properties.

Learnt from: chronark
PR: #2544
File: apps/api/src/pkg/ratelimit/client.ts:83-83
Timestamp: 2024-10-23T12:04:12.530Z
Learning: In the metrics.emit call, it's acceptable to set mode to "cloudflare" when using Cloudflare's rate limiter.

Learnt from: chronark
PR: #3474
File: go/apps/api/routes/v2_keys_verify_key/200_test.go:380-380
Timestamp: 2025-07-14T08:15:56.747Z
Learning: In the Unkey codebase, there is a mechanism to set the server's time via a header for test control, which helps make ratelimit tests deterministic instead of time-dependent. This is useful for preventing flaky tests where the second request might hit a new ratelimit window.

🪛 markdownlint-cli2 (0.17.2)
go/benchmarks/README.md

7-7: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


15-15: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


19-19: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


27-27: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


30-30: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


31-31: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


35-35: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


36-36: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


39-39: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


40-40: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)


45-45: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


46-46: Lists should be surrounded by blank lines

(MD032, blanks-around-lists)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test Go API Local / Test
  • GitHub Check: Build / Build
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Packages / Test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (8)
go/benchmarks/README.md (2)

1-49: LGTM! Comprehensive documentation for the benchmark suite.

The documentation provides clear setup instructions, usage examples, and configuration details for both benchmark scripts. The structure is logical and covers all necessary information for users to run the benchmarks effectively.


16-17: Endpoints Confirmed: README.md Matches Benchmark Scripts

The benchmark script at go/benchmarks/ratelimit.js indeed calls:

  • /v1/ratelimits.limit (plural) on api.unkey.dev
  • /v2/ratelimit.limit (singular) on api.unkey.com

No updates to go/benchmarks/README.md are necessary.

go/benchmarks/keyverify.js (3)

22-29: LGTM! Elegant load zone distribution logic.

The dynamic percentage calculation ensures even distribution across active load zones, with proper handling of remainder percentages for the last zone.


48-54: LGTM! Proper environment variable validation.

Clear error messages and early validation prevent runtime issues during test execution.


67-79: LGTM! Well-implemented API version randomization.

The 50/50 split between v1 and v2 APIs is correctly implemented with proper request tagging for metrics collection.

go/benchmarks/ratelimit.js (3)

46-46: Good addition of REGION parameter.

The region parameter provides useful tagging for metrics analysis, though it's not used in keyverify.js for consistency.


70-87: LGTM! Well-structured rate limiting benchmark logic.

The random user identifier selection and API version randomization provide good test coverage. The request payload structure is appropriate for rate limiting testing.


70-87: Naming difference is intentional—no changes needed.

Verified that the v2 route is defined as /v2/ratelimit.limit in go/apps/api/routes/register.go, its handler’s Path() method, and OpenAPI specs, while the v1 endpoint remains /v1/ratelimits.limit as used in benchmarks. The mismatch is intentional and aligns with existing API definitions.

@chronark chronark merged commit 1ae32de into main Jul 29, 2025
26 of 27 checks passed
@chronark chronark deleted the 07-29-chore_k6_benchmarks branch July 29, 2025 09:22
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