Skip to content

Commit 31a05e3

Browse files
authored
Merge branch 'main' into feat/WEB-WEB-555-optimize-docs
2 parents 2ca7f57 + 797fe72 commit 31a05e3

20 files changed

+630
-7
lines changed

cSpell.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,8 @@
100100
"Nikolas",
101101
"Supavisor",
102102
"inshellisense",
103-
"janedoe"
103+
"janedoe",
104+
"unindexed"
104105
],
105106
"patterns": [
106107
{

content/100-getting-started/index.mdx

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
Bolt,
1414
BorderBox,
1515
BoxTitle,
16+
Inspect,
1617
Database,
1718
Grid,
1819
LinkCard,
@@ -33,11 +34,12 @@ Explore our products that make it easy to build and scale data-driven applicatio
3334

3435
[**<Database />Prisma ORM**](/orm/overview/introduction/what-is-prisma) is a next-generation Node.js and TypeScript ORM that unlocks a new level of developer experience when working with databases thanks to its intuitive data model, automated migrations, type-safety & auto-completion.
3536

37+
[**<Inspect />Prisma Optimize**](/optimize/) helps you analyze queries, generate insights, and provides recommendations to make your database queries faster.
38+
3639
[**<Bolt />Prisma Accelerate**](/accelerate) is a global database cache with scalable connection pooling to make your queries fast.
3740

3841
[**<SignalStream />Prisma Pulse**](/pulse) allows you to react to database changes with type-safe model streams in real-time.
3942

40-
4143
</BorderBox>
4244

4345
</TopBlock>
@@ -195,3 +197,22 @@ Build real-time applications by subscribing to data changes in your database usi
195197
link="https://github.com/prisma/prisma-examples?tab=readme-ov-file#prisma-pulse"
196198
/>
197199
</Grid>
200+
201+
## <Inspect color="#16A394" width="27" height="24" /> Prisma Optimize
202+
203+
Make your database queries faster by using the insights and recommendations generated by Prisma Optimize.
204+
205+
<Grid>
206+
<LinkCard
207+
icon="fa-solid fa-arrow-right"
208+
title="Get started"
209+
desc="Add Optimize to your app to gather useful insights and receive recommendations to improve query performance."
210+
link="/optimize/getting-started"
211+
/>
212+
<LinkCard
213+
icon="fa-brands fa-github"
214+
title="Examples"
215+
desc="Explore our ready-to-run examples using Prisma Optimize."
216+
link="https://github.com/prisma/prisma-examples?tab=readme-ov-file#prisma-optimize"
217+
/>
218+
</Grid>

content/200-orm/200-prisma-client/100-queries/100-query-optimization-performance.mdx

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,17 @@ metaDescription: 'How Prisma optimizes queries under the hood'
55
tocDepth: 3
66
---
77

8-
<TopBlock>
9-
108
This guide describes ways to optimize query performance, debug performance issues, and how to tackle common performance issues such as the [n+1 problem](#solving-the-n1-problem).
119

12-
</TopBlock>
10+
:::tip
11+
12+
To debug slow queries, you can use [Prisma Optimize](/optimize) and follow the [recommendations](/optimize/recommendations) provided to improve query performance in your app.
13+
14+
:::
1315

1416
## Debugging performance issues
1517

16-
To help you debug and diagnose performance issues, you can [log query events at client level](/orm/prisma-client/observability-and-logging/logging#event-based-logging), which allows you to see the generated queries, parameters, and durations.
18+
To help you debug and diagnose performance issues, you can [log query events at client level](/orm/prisma-client/observability-and-logging/logging#event-based-logging), which allows you to see the generated queries, parameters, and durations.
1719

1820
Alternatively, if you are only interested in the time taken to run a query, you can implement [logging middleware](/orm/prisma-client/client-extensions/middleware/logging-middleware).
1921

content/500-platform/10-about.mdx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,33 @@ In each workspace, you can:
4242
- manage billing, i.e. select a [subscription plan](https://www.prisma.io/pricing?utm_source=docs&utm_medium=platform-docs), configure payment methods, or view the invoice history.
4343
- view the usage of your enabled PDP products across all projects in that workspace.
4444
- invite other users to collaborate in the workspace.
45+
- access the [Optimize dashboard](https://console.prisma.io/optimize?utm_source=docs&utm_medium=optimize-docs) to measure query performance and receive AI-powered recommendations.
46+
47+
#### Optimize
48+
49+
You can access Optimize within your [Prisma Data Platform account](https://console.prisma.io/optimize) workspace.
50+
51+
##### Accessing the Optimize dashboard
52+
53+
To access the Optimize dashboard in your desired workspace:
54+
55+
1. Click the **Optimize** tab on the left navigation.
56+
2. Click the **Launch Optimize** button.
57+
58+
##### Generating an Optimize API key
59+
60+
To obtain the Optimize API key:
61+
62+
1. Navigate to the workspace where you want to use Optimize.
63+
2. Ensure that Optimize is launched. If it isn't, click the **Launch Optimize** button.
64+
3. If it isn't launched, spot the text in the Optimize dashboard that says, "Start by creating your first API key __here__ and start using Optimize," and click the __here__ link.
65+
4. Click your profile name in the top right corner of the navbar.
66+
5. Select **Settings**.
67+
6. Click **Create API key**.
68+
7. Enter a name for the API key in the **Name** field, then click **Create**.
69+
8. Copy the API key and store it securely. This will be used in your project's [`.env` file](/optimize/getting-started#23-add-the-optimize-api-key-to-your-env-file) via the `"OPTIMIZE_API_KEY"`. Finally, click the **"I've stored it securely"** button.
70+
71+
You now have your Optimize API key.
4572

4673
### Project
4774

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
---
2+
title: 'Getting Started'
3+
metaTitle: 'Getting started with Prisma Optimize'
4+
metaDescription: 'Learn how to quickly set up and start using Prisma Optimize.'
5+
tocDepth: 3
6+
toc: true
7+
---
8+
9+
## Prerequisites
10+
11+
Before you begin with Prisma Optimize, ensure you have the following:
12+
13+
- A [Prisma Data Platform account](https://console.prisma.io).
14+
- A project using [Prisma Client](/orm/prisma-client) version `5.0.0` or higher (we recommend using the latest version).
15+
- A PostgreSQL, MySQL/MariaDB, CockroachDB, or MS SQL Server database.
16+
17+
:::note
18+
19+
Prisma Optimize is intended for use in local environments. Learn more in the [FAQ](/optimize/faq#can-i-use-prisma-optimize-in-production).
20+
21+
:::
22+
23+
## 1. Launch Optimize
24+
25+
1. Log in to your [Prisma Data Platform account](https://console.prisma.io/optimize?utm_source=docs&utm_medium=optimize-page).
26+
2. <a href="/platform/about#accessing-the-optimize-dashboard" target="_blank">Follow the instructions</a> to access and launch Prisma Optimize.
27+
28+
## 2. Add Optimize to your application
29+
30+
### 2.1. Update Your `schema.prisma` file
31+
32+
In the `generator` block of your Prisma schema, add the `tracing` preview feature:
33+
34+
```prisma
35+
generator client {
36+
provider = "prisma-client-js"
37+
previewFeatures = ["tracing"]
38+
}
39+
```
40+
41+
Then, generate the Prisma Client:
42+
43+
```bash
44+
npx prisma generate
45+
```
46+
47+
### 2.2. Install the Optimize Prisma Client extension
48+
49+
Install the latest versions of Prisma Client and the Optimize extension:
50+
51+
```bash
52+
npm install @prisma/client@latest @prisma/extension-optimize
53+
```
54+
55+
### 2.3. Add the Optimize API Key to your `.env` file
56+
57+
<a href="/platform/about#generating-an-optimize-api-key" target="_blank">Generate a Prisma Optimize API key</a> and add it to your `.env` file:
58+
59+
```bash
60+
OPTIMIZE_API_KEY="YOUR_OPTIMIZE_API_KEY"
61+
```
62+
63+
### 2.4. Extend your Prisma Client instance
64+
65+
Extend your existing Prisma Client instance with the Optimize extension:
66+
67+
```ts
68+
import { PrismaClient } from "@prisma/client";
69+
import { withOptimize } from "@prisma/extension-optimize";
70+
71+
const prisma = new PrismaClient().$extends(
72+
withOptimize({ token: process.env.OPTIMIZE_API_KEY }),
73+
);
74+
```
75+
76+
### 2.5. Use Prisma Optimize to generate insights
77+
78+
Follow these steps to start generating query insights with Prisma Optimize:
79+
80+
1. In the Optimize dashboard, click the **Start recording** button, then run your app and execute some Prisma queries while recording is active.
81+
2. After your app runs and generates insights based on the executed Prisma queries, click the **Stop recording** button.
82+
3. Explore [individual query details](/optimize/recordings#data-captured-in-a-recording-session) by clicking on them, and check the **Recommendations** tab for any suggested improvements to enhance query performance.
83+
84+
:::info
85+
Use [Prisma AI](/optimize/prisma-ai) to understand recommendations and apply them within your Prisma model context.
86+
:::
87+
88+
For a hands-on learning experience, try out the [step-by-step example](https://github.com/prisma/prisma-examples/tree/latest/optimize/starter).
89+
90+
## Need help?
91+
92+
If you need assistance, reach out in the `#help-and-questions` channel on our [Discord](https://pris.ly/discord), or connect with our community to see how others are using Optimize.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
---
2+
title: 'Recordings'
3+
metaTitle: 'Optimize: Recordings'
4+
metaDescription: "Learn about using Optimize's recording feature."
5+
tocDepth: 3
6+
toc: true
7+
---
8+
9+
The recordings feature helps developers debug and isolate sets of queries into distinct sessions, known as recordings. This targeted approach enables precise performance analysis and optimization by preventing the mixing of queries from different applications or test rounds, leading to clearer insights and more effective debugging.
10+
11+
## Managing a recording session
12+
13+
You can manually start and stop recording sessions via the [Optimize dashboard](https://console.prisma.io/optimize) by clicking the **Start Recording** and **Stop Recording** buttons.
14+
15+
:::warning
16+
A recording will automatically stop if the 10k query limit is reached or if the Prisma schema of the app is changed.
17+
:::
18+
19+
## Identifying a recording session
20+
21+
You can rename and tag your recording sessions for easy identification and context. Click on the default name of the session and type the desired name.
22+
23+
## Data captured in a recording session
24+
25+
Each recording session captures detailed insights about the queries executed in your app, including:
26+
27+
- All queries executed during the session.
28+
- The raw query generated and sent to the database by Prisma ORM as **Raw Query**.
29+
- The number of times a query pattern was executed, listed as **Count**.
30+
- [Query performance metrics](/optimize/performance-metrics).
31+
- Errors encountered during query execution.
32+
33+
Each recording can include up to 10k queries. There are no limits on storage retention.
34+
35+
## Recommendations from a recording session
36+
37+
When a recording session ends, Optimize generates recommendations such as:
38+
39+
- [Excessive number of rows returned](/optimize/recommendations/excessive-number-of-rows-returned)
40+
- [Full table scans caused by LIKE operations](/optimize/recommendations/full-table-scans-caused-by-like-operations)
41+
- [Queries on unindexed columns](/optimize/recommendations/queries-on-unindexed-columns)
42+
43+
:::info
44+
Use [Prisma AI](/optimize/prisma-ai) to ask follow-up questions about a recommendation.
45+
:::
46+
47+
Learn more about the recommendations generated by Optimize [here](/optimize/recommendations).
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
title: 'Excessive number of rows returned'
3+
metaTitle: 'Optimize Recommendations: Excessive number of rows returned'
4+
metaDescription: "Learn about the recommendation provided by Optimize for excessive number of rows returned."
5+
tocDepth: 3
6+
toc: true
7+
---
8+
9+
Optimize provides recommendations to help you identify and resolve performance issues caused by excessive number of rows returned from a query.
10+
11+
The following query targeting a `User` model does not provide a [`take` option](/orm/reference/prisma-client-reference#findmany):
12+
13+
```ts
14+
await prisma.user.findMany({ where: { email: "[email protected]" }})
15+
```
16+
17+
## What is the problem?
18+
19+
When a query is executed without specifying a limit, it will return all relevant rows, which can lead to several issues:
20+
21+
### User experience
22+
23+
- **Viewing data:** Users typically need only a portion of the data at any given time, not all of it at once.
24+
- **Impact on the user's device:** Displaying all the data at once can strain the user's device resources. For example, loading thousands of rows in a web application can slow down or freeze the browser, consuming significant memory and CPU resources.
25+
- **Waiting time:** Retrieving a large number of rows can significantly increase the time it takes to get the data from the database to the user's device.
26+
27+
### Resource Utilization
28+
29+
- **Unnecessary data load:** Processing more data than required wastes valuable resources.
30+
- **Memory usage:** Excessive memory consumption can lead to inefficiency and, in severe cases, cause the system to run out of memory, disrupting the service.
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
---
2+
title: 'Queries on unindexed columns'
3+
metaTitle: 'Optimize Recommendations: Queries on unindexed columns'
4+
metaDescription: "Learn about the recommendation provided by Optimize for queries on unindexed columns."
5+
tocDepth: 3
6+
toc: true
7+
---
8+
9+
Optimize provides recommendations to help you identify and resolve performance issues caused by missing database indexes.
10+
11+
The following queries targeting the `User` model use a [`where` property](/orm/prisma-client/queries/filtering-and-sorting) to filter on columns that do not have indexes:
12+
13+
```ts
14+
await prisma.user.findFirst({
15+
where: {
16+
name: "Marc"
17+
}
18+
})
19+
20+
await prisma.user.findFirst({
21+
where: {
22+
name: "Jon"
23+
}
24+
})
25+
26+
await prisma.user.count({
27+
where: {
28+
name: "Nikolas"
29+
}
30+
})
31+
```
32+
33+
## What is the problem?
34+
35+
An index allows the database to retrieve data more quickly, similar to how an index in a book helps you locate information without reading every page.
36+
37+
When using Prisma with a `where` property, if no indexes are defined for the relevant columns, the database may need to scan every row in the table (a *“full table scan”*) to find matches. This can be undesirable for several reasons:
38+
39+
### User experience
40+
41+
For large datasets, if the database must scan the entire table to find matching rows, users will experience longer waiting times.
42+
43+
### Resource utilization
44+
45+
- **High CPU usage:** Scanning large tables can significantly increase CPU usage, degrading overall system performance.
46+
- **Memory consumption:** More memory is required to process and store data during a full table scan.
47+
- **Disk I/O:** Full table scans increase disk input/output operations, potentially slowing down other database activities.
48+
49+
:::warning
50+
51+
While these issues might not appear in development due to smaller datasets, they can become *significant* problems in production, where datasets are typically much larger.
52+
53+
:::
54+
55+
56+
## More on database indexes
57+
58+
### How indexes work
59+
60+
Indexes create a data structure that stores the indexed column's values along with pointers to the corresponding rows in the table. When you query the database using an indexed column, the database can use this index to quickly locate the relevant rows instead of scanning the entire table.
61+
62+
### The trade-offs of indexing
63+
64+
- **Space vs. time:** Indexing requires additional storage space to save index data, but it significantly speeds up data retrieval.
65+
- **Update overhead:** Every time data is added to, updated in, or removed from your table, there is an overhead to keep the indexes up to date, which can slow down write operations.
66+
67+
### When to use indexes
68+
69+
- **Large datasets:** Indexes are particularly beneficial for tables with a large number of rows.
70+
- **Frequent queries with filtering or sorting:** Use indexes on columns that are frequently used for [filtering or sorting](/orm/prisma-client/queries/filtering-and-sorting#filtering).
71+
- **Looking up related data:** Use indexes on foreign key columns to speed up the retrieval of related records, such as when using [`include`](/orm/prisma-client/queries/relation-queries#include-a-relation).
72+
73+
### When not to use indexes
74+
75+
- **Small tables:** For tables with very few rows, the overhead of maintaining indexes might not be worth the performance gain.
76+
- **Write-heavy tables:** Indexes can slow down write operations (`create`, `update`, `delete`) because the index needs to be updated as well. Avoid excessive indexing on models with frequent write operations.
77+
- **Infrequently accessed tables:** If a table is rarely accessed, the benefits of indexing may not justify the overhead.
78+
- **Columns with large data:** Indexing columns with large data can lead to higher storage requirements and might not provide significant performance improvements.
79+
- **Rarely filtered columns:** If a table is often accessed but rarely filtered by a specific column, creating an index on that column may not be beneficial.
80+
81+
:::warning
82+
83+
Even if you index a column, the database may not always use it. Many database management systems, such as PostgreSQL and MySQL, have a *query optimizer* that evaluates multiple execution plans and selects the one it estimates to be most efficient. In some cases, this may involve ignoring an existing index in favor of a different execution plan that it determines will perform better for that specific query.
84+
85+
:::

0 commit comments

Comments
 (0)