开源的用户管理解决方案,自带前端组件和管理后台。
Go to file
BilalG1 b5b311554b
Metrics Endpoint Speed (#966)
<img width="567" height="249" alt="Screenshot 2025-10-20 at 11 23 10 AM"
src="https://github.com/user-attachments/assets/340df844-f619-489f-8d41-cc26bc165018"
/>
<img width="595" height="255" alt="Screenshot 2025-10-20 at 11 24 00 AM"
src="https://github.com/user-attachments/assets/9321bda1-e6f0-4f53-8c6b-e29d0fc16038"
/>

<!--

Make sure you've read the CONTRIBUTING.md guidelines:
https://github.com/stack-auth/stack-auth/blob/dev/CONTRIBUTING.md

-->

<!-- RECURSEML_SUMMARY:START -->
## High-level PR Summary
This PR optimizes the performance of user list and metrics endpoints by
refactoring SQL queries to use more efficient patterns. The changes
include rewriting queries to use `LATERAL` joins and CTEs with proper
filtering, extracting common user mapping logic into reusable functions,
and adding performance tests with SQL scripts to generate realistic test
data (10,000 mock users and activity events across 100 countries).

⏱️ Estimated Review Time: 30-90 minutes

<details>
<summary>💡 Review Order Suggestion</summary>

| Order | File Path |
|-------|-----------|
| 1 | `apps/e2e/tests/backend/performance/mock-users.sql` |
| 2 | `apps/e2e/tests/backend/performance/mock-metric-events.sql` |
| 3 | `apps/e2e/tests/backend/performance/users-list.test.ts` |
| 4 | `apps/backend/src/app/api/latest/users/crud.tsx` |
| 5 | `apps/backend/src/app/api/latest/internal/metrics/route.tsx` |
</details>



[![Need help? Join our
Discord](https://img.shields.io/badge/Need%20help%3F%20Join%20our%20Discord-5865F2?style=plastic&logo=discord&logoColor=white)](https://discord.gg/n3SsVDAW6U)


[![Analyze latest
changes](f22b2c44a1/?repo_owner=stack-auth&repo_name=stack-auth&pr_number=966)
<!-- RECURSEML_SUMMARY:END -->
<!-- ELLIPSIS_HIDDEN -->


----

> [!IMPORTANT]
> Optimize metrics and user list endpoints with SQL refactoring,
caching, and performance tests, adding a `CacheEntry` model and mock
data scripts.
> 
>   - **Performance Optimization**:
> - Refactor SQL queries in `route.tsx` to use `LATERAL` joins and CTEs
for efficient data retrieval.
> - Implement caching in `route.tsx` using `getOrSetCacheValue()` to
reduce database load.
>   - **Database Changes**:
> - Add `CacheEntry` model to `schema.prisma` and create corresponding
table and index in `migration.sql`.
> - Remove auto-migration metadata step from
`check-prisma-migrations.yaml`.
>   - **Testing**:
> - Add performance tests in `metrics.test.ts` to benchmark metrics and
user endpoints.
> - Create mock data scripts `mock-users.sql` and
`mock-metric-events.sql` for testing with 10,000 users and events across
100 countries.
>   - **Miscellaneous**:
> - Update `db-migrations.ts` to include new migration file generation
logic.
>     - Add `cache.tsx` for caching logic implementation.
> 
> <sup>This description was created by </sup>[<img alt="Ellipsis"
src="https://img.shields.io/badge/Ellipsis-blue?color=175173">](https://www.ellipsis.dev?ref=stack-auth%2Fstack-auth&utm_source=github&utm_medium=referral)<sup>
for 4d9be71063. You can
[customize](https://app.ellipsis.dev/stack-auth/settings/summaries) this
summary. It will automatically update as commits are pushed.</sup>

----


<!-- ELLIPSIS_HIDDEN -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Metrics now use a cache layer with per-entry TTL and tenancy-aware
loaders.

* **Bug Fixes**
* Improved accuracy of daily active and related metrics with
tenancy-aware counting and more robust last-active computation.

* **Performance**
* Faster metrics responses via batched reads and cache-backed endpoints.

* **Tests**
* Added end-to-end performance benchmarks and SQL seed scripts for
metrics/user load testing.

* **Chores**
* DB migration added support for cached entries; CI migration check flow
adjusted; migration tooling improved.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Konsti Wohlwend <n2d4xc@gmail.com>
2025-11-05 16:24:04 -08:00
.changeset chore: update package versions 2024-06-07 13:32:12 +02:00
.claude Normalize emails on sign-in 2025-10-29 17:58:29 -07:00
.devcontainer Customizable ports (#962) 2025-10-20 15:24:47 -07:00
.github Metrics Endpoint Speed (#966) 2025-11-05 16:24:04 -08:00
.vscode Customizable ports (#962) 2025-10-20 15:24:47 -07:00
apps Metrics Endpoint Speed (#966) 2025-11-05 16:24:04 -08:00
claude Delete Workflows app (thank you Vercel) 2025-10-29 18:09:38 -07:00
configs Fix dev 2025-10-10 10:32:34 -07:00
docker mirrored qstash image (#968) 2025-10-21 18:28:22 -07:00
docs [Docs][Site] + [Dashboard][UI] - Adds docs to Stack Companion (#869) 2025-10-30 20:01:30 -05:00
examples chore: update package versions 2025-10-29 18:13:53 -07:00
packages add stackAuthComponent to convex readme (#999) 2025-11-04 22:13:27 -08:00
patches Fix MS OAuth (#457) 2025-02-21 19:39:22 +01:00
scripts Watch fewer open files during development 2025-10-20 18:03:55 -07:00
.dockerignore Vanilla JS client library (#408) 2025-02-08 02:31:03 +01:00
.gitignore Customizable ports (#962) 2025-10-20 15:24:47 -07:00
AGENTS.md Fix lint 2025-10-30 00:05:42 -07:00
CLAUDE.md payments schema changes, ledger algo, stackable items (#862) 2025-08-27 20:13:22 +00:00
CONTRIBUTING.md Update CONTRIBUTING.md 2025-10-20 19:14:06 -07:00
LICENSE Fix user hooks 2025-06-22 19:32:52 -07:00
package.json Customizable ports (#962) 2025-10-20 15:24:47 -07:00
pnpm-lock.yaml Fix Docker build 2025-10-22 17:14:46 -07:00
pnpm-workspace.yaml Move examples to their own folder (#77) 2024-06-16 14:58:10 +02:00
README.md Fix: Updated doc link in README.md (#827) 2025-08-04 15:25:29 -07:00
turbo.json Sort projects 2025-08-31 12:59:14 -07:00
vercel.json Fix typo 2025-02-28 12:03:52 -08:00
vitest.shared.ts Speed up Vitest 2025-09-03 10:44:52 -07:00
vitest.workspace.ts Convex implementation (#913) 2025-09-24 19:16:45 +00:00

Stack Logo

📘 Docs | ☁️ Hosted Version | Demo | 🎮 Discord

Stack Auth: The open-source auth platform

Stack Auth is a managed user authentication solution. It is developer-friendly and fully open-source (licensed under MIT and AGPL).

Stack Auth gets you started in just five minutes, after which you'll be ready to use all of its features as you grow your project. Our managed service is completely optional and you can export your user data and self-host, for free, at any time.

We support Next.js, React, and JavaScript frontends, along with any backend that can use our REST API. Check out our setup guide to get started.

Stack Auth Setup

Table of contents

How is this different from X?

Ask yourself about X:

  • Is X open-source?
  • Is X developer-friendly, well-documented, and lets you get started in minutes?
  • Besides authentication, does X also do authorization and user management (see feature list below)?

If you answered "no" to any of these questions, then that's how Stack Auth is different from X.

Features

To get notified first when we add new features, please subscribe to our newsletter.

<SignIn/> and <SignUp/>

Authentication components that support OAuth, password credentials, and magic links, with shared development keys to make setup faster. All components support dark/light modes.
Sign-in component

Idiomatic Next.js APIs

We build on server components, React hooks, and route handlers.
Dark/light mode

User dashboard

Dashboard to filter, analyze, and edit users. Replaces the first internal tool you would have to build.
User dashboard

Account settings

Lets users update their profile, verify their e-mail, or change their password. No setup required.
Account settings component

Multi-tenancy & teams

Manage B2B customers with an organization structure that makes sense and scales to millions.
Selected team switcher component

Role-based access control

Define an arbitrary permission graph and assign it to users. Organizations can create org-specific roles.
RBAC

OAuth Connections

Beyond login, Stack Auth can also manage access tokens for third-party APIs, such as Outlook and Google Calendar. It handles refreshing tokens and controlling scope, making access tokens accessible via a single function call.
OAuth tokens

Passkeys

Support for passwordless authentication using passkeys, allowing users to sign in securely with biometrics or security keys across all their devices.
OAuth tokens

Impersonation

Impersonate users for debugging and support, logging into their account as if you were them.
Webhooks

Webhooks

Get notified when users use your product, built on Svix.
Webhooks

Automatic emails

Send customizable emails on triggers such as sign-up, password reset, and email verification, editable with a WYSIWYG editor.
Email templates

User session & JWT handling

Stack Auth manages refresh and access tokens, JWTs, and cookies, resulting in the best performance at no implementation cost.
User button

M2M authentication

Use short-lived access tokens to authenticate your machines to other machines.
M2M authentication

📦 Installation & Setup

To install Stack Auth in your Next.js project (for React, JavaScript, or other frameworks, see our complete documentation):

  1. Run Stack Auth's installation wizard with the following command:

    npx @stackframe/init-stack@latest
    

    If you prefer not to open a browser during setup (useful for CI/CD environments or restricted environments):

    npx @stackframe/init-stack@latest --no-browser
    
  2. Then, create an account on the Stack Auth dashboard, create a new project with an API key, and copy its environment variables into the .env.local file of your Next.js project:

    NEXT_PUBLIC_STACK_PROJECT_ID=<your-project-id>
    NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY=<your-publishable-client-key>
    STACK_SECRET_SERVER_KEY=<your-secret-server-key>
    
  3. That's it! You can run your app with npm run dev and go to http://localhost:3000/handler/signup to see the sign-up page. You can also check out the account settings page at http://localhost:3000/handler/account-settings.

Check out the documentation for a more detailed guide.

🌱 Some community projects built with Stack Auth

Have your own? Happy to feature it if you create a PR or message us on Discord.

Templates

Examples

🏗 Development & Contribution

This is for you if you want to contribute to the Stack Auth project or run the Stack Auth dashboard locally.

Important: Please read the contribution guidelines carefully and join our Discord if you'd like to help.

Requirements

  • Node v20
  • pnpm v9
  • Docker

Setup

Pre-populated .env files for the setup below are available and used by default in .env.development in each of the packages. (Note: If you're creating a production build (eg. with pnpm run build), you must supply the environment variables manually.)

In a new terminal:

pnpm install

# Build the packages and generate code. We only need to do this once, as `pnpm dev` will do this from now on
pnpm build:packages
pnpm codegen

# Start the dependencies (DB, Inbucket, etc.) as Docker containers, seeding the DB with the Prisma schema
# Make sure you have Docker (or OrbStack) installed and running
pnpm restart-deps
# restart-deps is the same as:
#   pnpm stop-deps  (if the containers are already running)
#   pnpm start-deps

# Start the dev server
pnpm dev
# For systems with limited resources, you can run a minimal development setup with just the backend and dashboard
# pnpm run dev:basic

# In a different terminal, run tests in watch mode
pnpm test

You can now open the dev launchpad at http://localhost:8100. From there, you can navigate to the dashboard at http://localhost:8101, API on port 8102, demo on port 8103, docs on port 8104, Inbucket (e-mails) on port 8105, and Prisma Studio on port 8106. See the dev launchpad for a list of all running services.

Your IDE may show an error on all @stackframe/XYZ imports. To fix this, simply restart the TypeScript language server; for example, in VSCode you can open the command palette (Ctrl+Shift+P) and run Developer: Reload Window or TypeScript: Restart TS server.

You can also open Prisma Studio to see the database interface and edit data directly:

pnpm run prisma studio

Database migrations

If you make changes to the Prisma schema, you need to run the following command to create a migration file:

pnpm run db:migration-gen

Chat with the codebase

Storia trained an AI on our codebase that can answer questions about using and contributing to Stack Auth.

Architecture overview

  graph TB
      Website[Your Website]
      User((User))
      Admin((Admin))
      subgraph "Stack Auth System"
          Dashboard[Stack Auth Dashboard<br/>/apps/dashboard]
          Backend[Stack Auth API Backend<br/>/apps/backend]
          Database[(PostgreSQL Database)]
          EmailService[Email Service<br/>Inbucket]
          WebhookService[Webhook Service<br/>Svix]
          StackSDK[Client SDK<br/>/packages/stack]
          subgraph Shared
              StackUI[Stack Auth UI<br/>/packages/stack-ui]
              StackShared[Stack Auth Shared<br/>/packages/stack-shared]
              StackEmails[Stack Auth Emails<br/>/packages/stack-emails]
          end
      end
      Admin --> Dashboard
      User --> Website
      Website --> StackSDK
      Backend --> Database
      Backend --> EmailService
      Backend --> WebhookService
      Dashboard --> Shared
      Dashboard --> StackSDK
      StackSDK --HTTP Requests--> Backend
      StackSDK --> Shared
      Backend --> Shared
      classDef container fill:#1168bd,stroke:#0b4884,color:#ffffff
      classDef database fill:#2b78e4,stroke:#1a4d91,color:#ffffff
      classDef external fill:#999999,stroke:#666666,color:#ffffff
      classDef deprecated stroke-dasharray: 5 5
      class Dashboard,Backend,EmailService,WebhookService,Website container
      class Database database

Thanks to CodeViz for generating the diagram!

❤ Contributors