Skip to content

Commit

Permalink
Improve Pulse docs: "What is Pulse?" and "Getting started" (#5976)
Browse files Browse the repository at this point in the history
* small changes

* update getting started

* Optimised images with calibre/image-actions

* Update content/400-pulse/100-what-is-pulse.mdx

Co-authored-by: Jon Harrell <4829245+jharrell@users.noreply.github.com>

* incorporate feedback

* Update content/400-pulse/100-what-is-pulse.mdx

Co-authored-by: Jon Harrell <4829245+jharrell@users.noreply.github.com>

* Update content/400-pulse/100-what-is-pulse.mdx

Co-authored-by: Petra Donka <donkapetra@gmail.com>

* incorporate feedback

* Update content/400-pulse/200-getting-started.mdx

Co-authored-by: Petra Donka <donkapetra@gmail.com>

* Update content/400-pulse/200-getting-started.mdx

Co-authored-by: Petra Donka <donkapetra@gmail.com>

* incorporate feedback

* Update content/400-pulse/200-getting-started.mdx

Co-authored-by: Petra Donka <donkapetra@gmail.com>

* Update content/400-pulse/200-getting-started.mdx

Co-authored-by: Petra Donka <donkapetra@gmail.com>

* incorporate feedback

* incorporate feedback

* incorporate feedback

* Update content/400-pulse/200-getting-started.mdx

* Update content/400-pulse/100-what-is-pulse.mdx

* Update content/400-pulse/100-what-is-pulse.mdx

Co-authored-by: Jon Harrell <4829245+jharrell@users.noreply.github.com>

* incorporate feedback

* update images

* Optimised images with calibre/image-actions

* update illustration

* update illustration

* Optimised images with calibre/image-actions

* fix typos

* Update content/400-pulse/200-getting-started.mdx

Co-authored-by: Petra Donka <donkapetra@gmail.com>

* update illustration

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Jon Harrell <4829245+jharrell@users.noreply.github.com>
Co-authored-by: Petra Donka <donkapetra@gmail.com>
  • Loading branch information
4 people committed May 13, 2024
1 parent 6ead326 commit 165a58a
Show file tree
Hide file tree
Showing 5 changed files with 178 additions and 41 deletions.
88 changes: 78 additions & 10 deletions content/400-pulse/100-what-is-pulse.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,97 @@ tocDepth: 3
toc: true
---

<TopBlock>
## Overview

[Prisma Pulse](https://www.prisma.io/data-platform/pulse) is managed database-event infrastructure that captures and distributes your database events to your application. It simplifies subscribing to type-safe data changes with an extended [Prisma Client](/orm/prisma-client) to power real-time functionality.
[Prisma Pulse](https://www.prisma.io/data-platform/pulse) facilitates the implementation of event-driven workflows and architectures by providing managed infrastructure that captures databases events and distributes them to your applications.

</TopBlock>
It lets you subscribe to any changes happening in your database using [Prisma Client](/orm/prisma-client) to power **real-time use cases** in your applications, such as:

## How Prisma Pulse works
- chat and messaging
- sending onboarding emails
- data syncing (e.g. into a search index)
- social collaboration
- notifying users
- updating inventories
- managing payments
- live games, quizzes and polls
- ... and many other functionalities that require real-time updates

Prisma Pulse leverages Change Data Capture (CDC) to efficiently observe and capture database changes as they occur. By monitoring the database's transaction log, Prisma Pulse identifies change events like inserts, updates, and deletes without impacting the database's performance.
Prisma Pulse integrates with [Prisma ORM](/orm) and lets you subscribe to database changes easily _and_ in a type-safe way using Prisma Client.

The captured events are processed, evaluated, and swiftly distributed to relevant client subscriptions ensuring your applications stay synchronized with the latest database state.
Here's the brief overview of how Pulse works:

This eliminates the need for complex polling or manual data synchronization, saving you development time and effort.
### 1. Subscribe to database changes with Prisma Client

![What is Pulse](/img/pulse/what-is-pulse.png)
In this example, we subscribe to _all_ changes that are happening on the `User` table in the database:

## What you can build with Prisma Pulse
```ts
// subscribe to all changes on the `User` table
const subscription = await prisma.user.subscribe()

// wait for new events to arrive
for await (let event of subscription) {

// log the details about an event to the terminal
console.log(`Something happened in the database: `)
console.log(event)
}
```

### 2. A database event happens

A change is made to the table we've previously subscribed to. In this case, a new row is added to the `User` table.

![](/img/pulse/user-insert.png)

This change can happen from anywhere, the same app that uses Prisma Client to subscribe to changes, a different application or microserivce, a database GUI or any other SQL client (like `psql`).

### 3. The database event is propagated to all subscribers

Prisma Pulse propagates the event to all subscribers. In this case, the application from step 1. receives the event and logs its value to the terminal:

``` no-copy
Something happened in the database:
{
"action": "create",
"created": {
"id": 1,
"email": "test@prisma.io",
"name": "test"
}
}
```

## Why Prisma Pulse?

Building real-time functionality based on changes that occur in your database can be very complicated. Common approaches like _polling_, implementing _application-level updates_ or using _additional infrastructure_ (like Apache Kafka or RabbitMQ) either don't scale, are very costly or come with substantial development and maintenance overhead.

Instead, Prisma Pulse is based on the idea of _unidirectional data flow_ which is implemented via [Change Data Capture](https://en.wikipedia.org/wiki/Change_data_capture) (CDC). CDC gets rid of the deficiencies of the previously mentioned approaches and solves the problem of reacting to database events in a robust and elegant manner.

Here is an overview of the main features Prisma Pulse provides:

- Reacting to database changes with type-safe model subscriptions
- Unidirectional data flow via Change Data Capture
- Great DX integrated with usage of Prisma ORM (easy setup, development and maintenance)
- Works with your existing database
- Insights dashboard lets you view and understand all database events captured by Pulse
- Enable, disable and manage Pulse via the [Platform CLI](/platform/platform-cli/)

## How does Prisma Pulse work?

Prisma Pulse uses CDC to efficiently observe and capture database changes as they occur. By monitoring the database's transaction log (e.g. the Write-Ahead-Log in PostgreSQL), Prisma Pulse identifies database change events like _inserts_, _updates_, and _deletes_ without impacting the database's performance.

The captured events are processed, evaluated, and distributed to all Prisma Client instances that subscribed to them:

![What is Pulse](/img/pulse/unidirectional-data-flow.png)

## What can you build with Prisma Pulse?

Prisma Pulse can power real-time functionality like chat, notifications, data broadcast, data synchronization, and more. It's ideal for ensuring data consistency in distributed systems, enhancing real-time user experiences.

![Prisma Pulse use-cases](/img/pulse/pulse-usecase.png)

## Examples
## Example projects

Here are a few example projects using Prisma Pulse:

Expand Down
131 changes: 100 additions & 31 deletions content/400-pulse/200-getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ tocDepth: 4
toc: true
---


## Prerequisites

<Admonition type="info">
Expand All @@ -17,19 +16,46 @@ Prisma Pulse currently supports PostgreSQL. We'd love to hear [which databases](

To get started with Pulse, you will need the following:

- A [Prisma Data Platform workspace](https://console.prisma.io).
- [Prisma Client](/orm/prisma-client) version `4.16.1` or higher and [`@prisma/extension-pulse`](https://www.npmjs.com/package/@prisma/extension-pulse) version `1.0.1` or higher.
- A publicly accessible PostgreSQL (version 12+) database with [logical replication](https://www.postgresql.org/docs/current/logical-replication-quick-setup.html) enabled. View our [setup guide](/pulse/database-setup/general-database-instructions#enable-logical-replication) on configuring logical replication for your database.
- A [Prisma Data Platform](https://console.prisma.io) account
- The **connection string** of a Pulse-ready database (if you don't have one yet, you can configure your database the instructions [here](/pulse/database-setup) or [use a Railway template](https://railway.app/template/pulse-pg?referralCode=VQ09uv))

## 1. Enable Pulse in the Platform Console

### 1.1. Choose the environment you want to enable Pulse for

Open the [Platform Console](https://console.prisma.io), navigate to your workspace of choice, then select the project and choose the environment in which you want to enable Pulse.

If you don't have a project yet in your workspace, you can create a new one.

### 1.2. Enable Pulse

In the project environment of your choice, click the **Enable Pulse** button.

## 1. Enable Pulse
### 1.3. Configure Pulse

Navigate to your Prisma Data Platform project, choose an environment, and enable Pulse. We'll connect to your database and verify connectivity during setup.
The Pulse **Setup** screen requires you to:

> Once enabled, you'll be prompted to generate an API key that you'll use in your extended Prisma Client to authenticate requests. Store this API key in your application's `.env` file:
>
> ```env file=.env showLineNumbers
> PULSE_API_KEY="your_secure_pulse_api_key"
> ```
- provide your **Database connection string**
- select a **Region** where Pulse should be hosted
- decide whether you want to use the **Automatic setup** for [**Database replication**](/pulse/concepts#logical-replication) (only available on paid plans)

When you're done with that, click the **Enable Pulse** button at the bottom of the screen. This will test the connectivity to your database.

### 1.4. Generate an API key

<Admonition>

If you already have an API key for your current environment, you can skip this step und use the existing API key for using Prisma Pulse.

</Admonition>

You can generate an API key by clicking the **Generate API key** button. Store the API key in a secure location or add it to the `.env` file of your project:

```env file=.env
PULSE_API_KEY="your_secure_pulse_api_key"
```

You won't be able to access the same API key again afterwards.

## 2. Add Pulse to your application

Expand All @@ -43,10 +69,10 @@ Pulse requires [Prisma Client](/orm/prisma-client) version `4.16.1` or higher an

</Admonition>

Install the latest version of Prisma Client and the Pulse Client extension
Install the Pulse Client extension:

```bash
npm install @prisma/client@latest @prisma/extension-pulse@latest
```terminal
npm install @prisma/extension-pulse@latest
```

### 2.2. Extend your Prisma Client instance with the Pulse extension
Expand All @@ -62,46 +88,89 @@ const prisma = new PrismaClient().$extends(
)
```

<Admonition type="note">

You stored this API key in your .env file after [enabling Pulse](#1-enable-pulse). If needed, you can navigate to your respective project environment and generate a new API key.

</Admonition>

### 2.3. Create your first Pulse subscription

With the Pulse extension applied, you can use Pulse's `subscribe()` method on any model defined in your Prisma Schema to subscribe to data change events.

In the below example, a subscription is made to a `notification` model that listens for _any_ change event on that table:
In the below example, it is assumed that your Prisma schema has a `User` model. A subscription is made to that `User` model that listens for _any_ change event on that table:

```ts
const prisma = new PrismaClient().$extends(withPulse({ apiKey: apiKey }))
<TabbedContent code>
<TabItem value="Subscription">

```ts highlight=9-13;add
import { PrismaClient } from '@prisma/client'
import { withPulse } from '@prisma/extension-pulse'

const prisma = new PrismaClient().$extends(
withPulse({ apiKey: process.env.PULSE_API_KEY })
)

async function main() {
const subscription = await prisma.notification.subscribe()
const subscription = await prisma.user.subscribe()

for await (const event of subscription) {
console.log('just received a notification:', event)
console.log('just received an event:', event)
}
}

main()
```

All done! You've successfully added Pulse to your application. Explore next steps to learn more.
</TabItem>

<TabItem value="Prisma schema">

```prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
```

</TabItem>

</TabbedContent>

## 3. Test your subscription

After running the code snippet above, you can test the subscription by _creating_, _updating_ or _deleting_ a `User` record in your database.

You can do that using Prisma Studio (by running `npx prisma studio`) or by using any other database client of your choice (like [Postico](https://eggerapps.at/postico2/) or `psql`).

If everything worked, you should see the event being logged to the terminal where you can the code snippet from above. 🎉

## Next steps

[Navigate to the API section](/pulse/api-reference) to explore available filtering options for Pulse's `subscribe()` method.
You can try out more filters on your Pulse subscription, for example:

**Subscribe only to `create` events**:

```ts
const subscription = await prisma.notification.subscribe({
create: {
userId: 123, // subscribe to all notifications created for the user with ID 123
},
const subscription = await prisma.user.subscribe({
create: { },
})
```

**Subscribe only to `update` events**:

```ts
const subscription = await prisma.user.subscribe({
update: { },
})
```


**Subscribe only to `delete` events**:

```ts
const subscription = await prisma.user.subscribe({
delete: { },
})
```

Pulse offers even more fine-grained filters than these. You can explore these in the [API reference](/pulse/api-reference).

## Need help?

Reach out to us in the `#help-and-questions` channel on our [Discord](https://pris.ly/discord), or connect with our community to see how others are using Pulse.
Binary file added static/img/pulse/overview.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/img/pulse/unidirectional-data-flow.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/img/pulse/user-insert.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 165a58a

Please sign in to comment.