Skip to content

perf: create root key being slow#3554

Merged
chronark merged 1 commit intomainfrom
perf/create_root_key_slow
Jul 14, 2025
Merged

perf: create root key being slow#3554
chronark merged 1 commit intomainfrom
perf/create_root_key_slow

Conversation

@Flo4604
Copy link
Member

@Flo4604 Flo4604 commented Jul 14, 2025

What does this PR do?

Fixes # (issue)

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Insert auditlogs in bulk for performance

  • 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?

  • Test A
  • Test B

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

  • Refactor
    • Improved the efficiency of audit log insertion, reducing database operations and removing informational logging.
    • Enhanced identity lookup to ensure it is scoped to the current workspace when creating a root key.

@changeset-bot
Copy link

changeset-bot bot commented Jul 14, 2025

⚠️ No Changeset found

Latest commit: eeed27a

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

@vercel
Copy link

vercel bot commented Jul 14, 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 14, 2025 11:15am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 14, 2025 11:15am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 14, 2025

📝 Walkthrough

Walkthrough

The changes refactor audit log insertion in the dashboard app to use batch inserts for both logs and their targets, removing per-insert logging. Additionally, identity lookup in root key creation is now scoped to the current workspace. No exported function signatures were altered.

Changes

File(s) Change Summary
apps/dashboard/lib/audit.ts Refactored insertAuditLogs to batch insert audit logs and targets, removed logging, improved typing.
apps/dashboard/lib/trpc/routers/key/createRootKey.ts Modified identity lookup to require matching workspace ID, adjusted insertion to set workspace ID.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant AuditModule
    participant Database

    Caller->>AuditModule: insertAuditLogs(logs)
    AuditModule->>AuditModule: Accumulate logs and targets
    AuditModule->>Database: Bulk insert audit logs
    alt Targets exist
        AuditModule->>Database: Bulk insert audit log targets
    end
    Database-->>AuditModule: Confirmation
    AuditModule-->>Caller: Done
Loading
sequenceDiagram
    participant Caller
    participant RootKeyModule
    participant Database

    Caller->>RootKeyModule: createRootKey(userId, workspaceId)
    RootKeyModule->>Database: Find identity where externalId=userId AND workspaceId=workspaceId
    alt Identity not found
        RootKeyModule->>Database: Insert new identity with workspaceId
    end
    RootKeyModule->>Database: Create root key
    RootKeyModule->>Database: Insert audit logs
    Database-->>RootKeyModule: Confirmation
    RootKeyModule-->>Caller: Root key created
Loading

Possibly related PRs

Suggested labels

🕹️ oss.gg, :joystick: 150 points, hacktoberfest

Suggested reviewers

  • chronark
  • mcstepp
  • perkinsjr

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b3215f and eeed27a.

📒 Files selected for processing (2)
  • apps/dashboard/lib/audit.ts (3 hunks)
  • apps/dashboard/lib/trpc/routers/key/createRootKey.ts (4 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: ogzhanolguncu
PR: unkeyed/unkey#2872
File: apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts:36-39
Timestamp: 2025-04-08T09:34:24.576Z
Learning: In the Unkey dashboard, when making database queries involving workspaces, use `ctx.workspace.id` directly instead of fetching the workspace separately for better performance and security.
Learnt from: chronark
PR: unkeyed/unkey#2146
File: apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts:80-80
Timestamp: 2024-10-04T17:27:08.666Z
Learning: Ensure that audit log descriptions accurately reflect the action being performed, such as updating the `defaultPrefix`, and avoid incorrect references like 'name' when not applicable.
Learnt from: ogzhanolguncu
PR: unkeyed/unkey#2872
File: apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts:36-39
Timestamp: 2025-04-08T09:34:24.576Z
Learning: When querying or updating namespaces in the Unkey dashboard, always scope the operations to the current workspace using `eq(table.workspaceId, ctx.workspace.id)` to prevent cross-workspace access.
Learnt from: chronark
PR: unkeyed/unkey#2825
File: apps/dashboard/app/(app)/logs/components/table/logs-table.tsx:100-118
Timestamp: 2025-01-31T13:50:45.004Z
Learning: Sensitive data in logs is masked at the API layer (apps/api/src/pkg/middleware/metrics.ts) before being written to Clickhouse. This includes redacting API keys, plaintext values, and authorization headers using regex replacements.
Learnt from: chronark
PR: unkeyed/unkey#2180
File: apps/dashboard/lib/constants/workspace-navigations.tsx:56-118
Timestamp: 2024-10-04T20:44:38.489Z
Learning: When typing the `workspace` parameter in functions like `createWorkspaceNavigation`, prefer importing the `Workspace` type from the database module and picking the necessary keys (e.g., `features`) instead of redefining the interface.
apps/dashboard/lib/trpc/routers/key/createRootKey.ts (14)
Learnt from: chronark
PR: unkeyed/unkey#2693
File: apps/api/src/routes/v1_keys_updateKey.ts:350-368
Timestamp: 2024-11-29T15:15:47.308Z
Learning: In `apps/api/src/routes/v1_keys_updateKey.ts`, the code intentionally handles `externalId` and `ownerId` separately for clarity. The `ownerId` field will be removed in the future, simplifying the code.
Learnt from: ogzhanolguncu
PR: unkeyed/unkey#2872
File: apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts:36-39
Timestamp: 2025-04-08T09:34:24.576Z
Learning: In the Unkey dashboard, when making database queries involving workspaces, use `ctx.workspace.id` directly instead of fetching the workspace separately for better performance and security.
Learnt from: chronark
PR: unkeyed/unkey#2180
File: apps/dashboard/lib/constants/workspace-navigations.tsx:56-118
Timestamp: 2024-10-04T20:44:38.489Z
Learning: When typing the `workspace` parameter in functions like `createWorkspaceNavigation`, prefer importing the `Workspace` type from the database module and picking the necessary keys (e.g., `features`) instead of redefining the interface.
Learnt from: ogzhanolguncu
PR: unkeyed/unkey#2872
File: apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts:36-39
Timestamp: 2025-04-08T09:34:24.576Z
Learning: When querying or updating namespaces in the Unkey dashboard, always scope the operations to the current workspace using `eq(table.workspaceId, ctx.workspace.id)` to prevent cross-workspace access.
Learnt from: ogzhanolguncu
PR: unkeyed/unkey#3324
File: apps/dashboard/app/(app)/authorization/roles/components/table/components/actions/keys-table-action.popover.constants.tsx:17-18
Timestamp: 2025-06-19T11:48:05.070Z
Learning: In the authorization roles refactor, the RoleBasic type uses `roleId` as the property name for the role identifier, not `id`. This is consistent throughout the codebase in apps/dashboard/lib/trpc/routers/authorization/roles/query.ts.
Learnt from: chronark
PR: unkeyed/unkey#2294
File: apps/api/src/pkg/keys/service.ts:268-271
Timestamp: 2024-10-20T07:05:55.471Z
Learning: In `apps/api/src/pkg/keys/service.ts`, `ratelimitAsync` is a table relation, not a column selection. When querying, ensure that table relations are included appropriately, not as columns.
Learnt from: ogzhanolguncu
PR: unkeyed/unkey#3292
File: apps/dashboard/lib/vault.ts:80-97
Timestamp: 2025-06-02T11:08:56.397Z
Learning: The vault.ts file in apps/dashboard/lib/vault.ts is a duplicate of the vault package from the `api` directory and should be kept consistent with that original implementation.
Learnt from: ogzhanolguncu
PR: unkeyed/unkey#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: mcstepp
PR: unkeyed/unkey#3210
File: apps/dashboard/app/new/page.tsx:3-3
Timestamp: 2025-04-30T15:25:33.917Z
Learning: There are two different `getAuth` functions in the Unkey codebase with different purposes:
1. `@/lib/auth/get-auth` - Base function without redirects, used in special cases on the dashboard where redirect control is needed (like `/new` page) and within tRPC context
2. `@/lib/auth` - Helper function with redirects, used in most dashboard cases (approximately 98%)
Learnt from: ogzhanolguncu
PR: unkeyed/unkey#3196
File: apps/dashboard/lib/audit.ts:105-108
Timestamp: 2025-04-25T14:16:27.152Z
Learning: The dashboard app in the Unkey codebase uses direct console.* methods (console.info, console.error, etc.) for logging rather than a structured logger utility.
Learnt from: chronark
PR: unkeyed/unkey#3161
File: go/pkg/clickhouse/schema/databases/002_ratelimits/006_ratelimits_per_day_v1.sql:1-13
Timestamp: 2025-04-22T14:43:11.724Z
Learning: In the unkey project, the SQL files in clickhouse/schema/databases represent the current production schema and shouldn't be modified directly in PRs. Schema changes require dedicated migration scripts.
Learnt from: ogzhanolguncu
PR: unkeyed/unkey#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: unkeyed/unkey#2876
File: apps/dashboard/components/logs/datetime/constants.ts:96-96
Timestamp: 2025-02-06T17:41:47.228Z
Learning: In the Unkey codebase, avoid hardcoding IDs or indices that depend on array positions, as the arrays may be modified in the future. Instead, use methods like `find` with unique identifiers or properties to locate specific items.
Learnt from: Flo4604
PR: unkeyed/unkey#3151
File: go/apps/api/openapi/gen.go:221-233
Timestamp: 2025-04-18T20:01:33.812Z
Learning: For identity deletion operations in the Unkey API, identityId takes precedence over externalId when both are provided in the request body.
apps/dashboard/lib/audit.ts (1)
Learnt from: chronark
PR: unkeyed/unkey#2146
File: apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts:80-80
Timestamp: 2024-10-04T17:27:08.666Z
Learning: Ensure that audit log descriptions accurately reflect the action being performed, such as updating the `defaultPrefix`, and avoid incorrect references like 'name' when not applicable.
⏰ 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). (8)
  • GitHub Check: Test Packages / Test ./apps/dashboard
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Packages / Test ./internal/hash
  • GitHub Check: Test Packages / Test ./internal/resend
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/id
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (9)
apps/dashboard/lib/trpc/routers/key/createRootKey.ts (3)

2-2: Import addition supports workspace scoping functionality.

The and function import is correctly added to support the new workspace scoping condition in the identity lookup query.


104-105: Excellent security improvement with workspace scoping.

The identity lookup is now properly scoped to the current workspace using and(eq(table.workspaceId, ctx.workspace.id), eq(table.externalId, ctx.user.id)). This prevents cross-workspace access and aligns with the established security pattern in the codebase.


112-112: Minor formatting changes are appropriate.

The whitespace adjustments improve code readability without affecting functionality.

Also applies to: 120-120, 138-138, 147-147, 180-180

apps/dashboard/lib/audit.ts (6)

6-6: Appropriate type imports for batch insertion.

The auditLog and auditLogTarget types are correctly imported to support the new batch insertion arrays.


110-111: Well-structured batch accumulation arrays.

The arrays are properly typed using $inferInsert to accumulate audit logs and targets for bulk insertion.


115-129: Efficient audit log accumulation.

The refactored logic correctly accumulates audit log entries into the array instead of performing individual insertions, which will significantly improve performance.


131-133: Smart optimization for empty resources.

The early continue for logs with no resources avoids unnecessary processing and keeps the audit log targets array clean.


135-147: Effective target accumulation with spread operator.

The use of spread operator to accumulate multiple audit log targets from each log's resources is clean and efficient.


150-154: Optimal bulk insertion implementation.

The bulk insert operations are well-implemented:

  • Single insert for all audit logs
  • Conditional insert for audit log targets only if they exist
  • This approach will significantly reduce database round-trips and improve performance
✨ 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.

@github-actions
Copy link
Contributor

github-actions bot commented Jul 14, 2025

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

@vercel vercel bot temporarily deployed to Preview – dashboard July 14, 2025 11:15 Inactive
@graphite-app
Copy link

graphite-app bot commented Jul 14, 2025

Video gif. An elderly man in suspenders smiles as he holds up two thumbs as if saying good luck.  (Added via Giphy)

Copy link
Collaborator

looks good, let’s verify on vercel, then merge

@chronark chronark self-assigned this Jul 14, 2025
Copy link
Collaborator

nice work, took 1.6s with a ton of permissions now

@chronark chronark added this pull request to the merge queue Jul 14, 2025
Copy link
Member Author

Flo4604 commented Jul 14, 2025

Could be better but its fine for now I think

Merged via the queue into main with commit 16b5db4 Jul 14, 2025
32 checks passed
@chronark chronark deleted the perf/create_root_key_slow branch July 14, 2025 11:24
@graphite-app
Copy link

graphite-app bot commented Jul 14, 2025

Graphite Automations

"Post a GIF when PR approved" took an action on this PR • (07/14/25)

1 gif was posted to this PR based on Andreas Thomas's automation.

@coderabbitai coderabbitai bot mentioned this pull request Aug 13, 2025
18 tasks
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.

2 participants