Docs / Packages / Pulse
Pulse
Introduction
Pulse delivers at-a-glance insights into your application's performance and usage. With Pulse, you can track down bottlenecks like slow jobs and endpoints, find your most active users, and more.
Note
Pulse's recording side (recorders, ingest drivers, storage, the
pulse:*commands) is ported. The dashboard's cards are Livewire and Blade components, and laraflare's screens are Vue, so the package ships no cards and no dashboard view: you record and aggregate the data, and show it on your own Vue screens.
Installation
Warning
Pulse's first-party storage implementation currently requires a MySQL, MariaDB, or PostgreSQL database. If you are using a different database engine, you will need a separate MySQL, MariaDB, or PostgreSQL database for your Pulse data.
You may install Pulse using npm:
npm install @laraflare/pulse
Next, you should publish the Pulse configuration and migration files using the vendor:publish Artisan command:
npx artisan vendor:publish --provider="PulseServiceProvider"
Finally, you should run the migrate command in order to create the tables needed to store Pulse's data:
npx artisan migrate
Note
If you do not want to store Pulse data in your application's primary database, you may specify a dedicated database connection.
Configuration
Many of Pulse's configuration options can be controlled using environment variables. To see the available options, register new recorders, or configure advanced options, you may publish the config/pulse.ts configuration file:
npx artisan vendor:publish --tag=pulse-config
Dashboard
Authorization
The Pulse routes are protected by the 'viewPulse' authorization gate. By default, you will only be able to access them in the local environment, so you will need to configure authorization for your production environments by customizing the 'viewPulse' gate. You can accomplish this within your application's app/Providers/AppServiceProvider.ts file:
import { Gate } from '@laraflare/framework';
import { User } from '../Models/User';
/**
* Bootstrap any application services.
*/
override boot(): void {
Gate.define('viewPulse', (user: User) => {
return user.isAdmin();
});
// ...
}
Resolving Users
For data that describes your users, such as application usage, Pulse will only record the user's ID. When resolving users, Pulse will read the name and email fields from your default authenticatable model.
You may customize the fields and avatar by invoking the Pulse.user method within your application's AppServiceProvider.
The user method accepts a closure which will receive the authenticatable model to be displayed and should return an object containing name, extra, and avatar information for the user:
import { Pulse } from '@laraflare/pulse';
/**
* Bootstrap any application services.
*/
override boot(): void {
Pulse.user((user) => ({
name: user.name,
extra: user.email,
avatar: user.avatar_url,
}));
// ...
}
Note
You may completely customize how the authenticated user is captured and retrieved by implementing the
ResolvesUserscontract and binding it in laraflare's service container.
Capturing Entries
Most Pulse recorders will automatically capture entries based on framework events dispatched by laraflare. However, the servers recorder must poll for information regularly. To use it, you must run the pulse:check daemon on all of your individual application servers:
npx artisan pulse:check
Note
To keep the
pulse:checkprocess running permanently in the background, you should use a process monitor to ensure that the command does not stop running. A Cloudflare Worker cannot hold a long-lived process, so run it on a server of your own.
As the pulse:check command is a long-lived process, it will not see changes to your codebase without being restarted. You should gracefully restart the command by calling the pulse:restart command during your application's deployment process:
npx artisan pulse:restart
Note
Pulse uses the cache to store restart signals, so you should verify that a cache driver is properly configured for your application before using this feature.
Recorders
Recorders are responsible for capturing entries from your application to be recorded in the Pulse database. Recorders are registered and configured in the recorders section of the Pulse configuration file, a map keyed by the recorder class:
recorders: new Map([
[SlowRequests, {
enabled: env('PULSE_SLOW_REQUESTS_ENABLED', true),
// ...
}],
]),
Patterns in a recorder's ignore, threshold and groups options are regular expressions.
Cache Interactions
The CacheInteractions recorder captures information about the cache hits and misses occurring in your application.
You may optionally adjust the sample rate and ignored key patterns.
You may also configure key grouping so that similar keys are grouped as a single entry. For example, you may wish to remove unique IDs from keys caching the same type of information. Groups are configured using a regular expression to "find and replace" parts of the key. An example is included in the configuration file:
[CacheInteractions, {
// ...
groups: {
// '/:\\d+/': ':*',
},
}],
The first pattern that matches will be used. If no patterns match, then the key will be captured as-is.
Exceptions
The Exceptions recorder captures information about reportable exceptions occurring in your application.
You may optionally adjust the sample rate and ignored exception patterns. You may also configure whether to capture the location that the exception originated from. If the same exception occurs in multiple locations then it will be recorded once for each unique location.
Queues
The Queues recorder captures information about your application's queues, including the number of jobs queued, processing, processed, released, and failed.
You may optionally adjust the sample rate and ignored jobs patterns.
Slow Jobs
The SlowJobs recorder captures information about slow jobs occurring in your application.
You may optionally adjust the slow job threshold, sample rate, and ignored job patterns.
You may have some jobs that you expect to take longer than others. In those cases, you may configure per-job thresholds:
[SlowJobs, {
// ...
threshold: {
'#^GenerateYearlyReports$#': 5000,
default: env('PULSE_SLOW_JOBS_THRESHOLD', 1000),
},
}],
If no regular expression patterns match the job's class name, then the 'default' value will be used.
Slow Outgoing Requests
The SlowOutgoingRequests recorder captures information about outgoing HTTP requests made using laraflare's HTTP client that exceed the configured threshold.
You may optionally adjust the slow outgoing request threshold, sample rate, and ignored URL patterns.
You may have some outgoing requests that you expect to take longer than others. In those cases, you may configure per-request thresholds:
[SlowOutgoingRequests, {
// ...
threshold: {
'#backup.zip$#': 5000,
default: env('PULSE_SLOW_OUTGOING_REQUESTS_THRESHOLD', 1000),
},
}],
If no regular expression patterns match the request's URL, then the 'default' value will be used.
You may also configure URL grouping so that similar URLs are grouped as a single entry. For example, you may wish to remove unique IDs from URL paths or group by domain only. Groups are configured using a regular expression to "find and replace" parts of the URL:
[SlowOutgoingRequests, {
// ...
groups: {
'#^https://api\\.github\\.com/repos/.*$#': 'api.github.com/repos/*',
'#^https?://([^/]*).*$#': '\\1',
'#/\\d+#': '/*',
},
}],
The first pattern that matches will be used. If no patterns match, then the URL will be captured as-is.
Slow Queries
The SlowQueries recorder captures any database queries in your application that exceed the configured threshold.
You may optionally adjust the slow query threshold, sample rate, and ignored query patterns. You may also configure whether to capture the query location. If the same query is made in multiple locations then it will be recorded once for each unique location.
You may have some queries that you expect to take longer than others. In those cases, you may configure per-query thresholds:
[SlowQueries, {
// ...
threshold: {
'#^insert into `yearly_reports`#': 5000,
default: env('PULSE_SLOW_QUERIES_THRESHOLD', 1000),
},
}],
If no regular expression patterns match the query's SQL, then the 'default' value will be used.
Slow Requests
The SlowRequests recorder captures information about requests to your application that exceed the configured threshold, which is 1,000ms by default.
You may optionally adjust the slow route threshold, sample rate, and ignored paths.
You may have some requests that you expect to take longer than others. In those cases, you may configure per-request thresholds:
[SlowRequests, {
// ...
threshold: {
'#^/admin/#': 5000,
default: env('PULSE_SLOW_REQUESTS_THRESHOLD', 1000),
},
}],
If no regular expression patterns match the request's URL, then the 'default' value will be used.
Servers
The Servers recorder captures CPU, memory, and storage usage of the servers that power your application. This recorder requires the pulse:check command to be running on each of the servers you wish to monitor.
Each reporting server must have a unique name. By default, Pulse will use the machine's host name. If you wish to customize this, you may set the server_name option of the recorder, for example from an environment variable:
PULSE_SERVER_NAME=load-balancer
The Pulse configuration file also allows you to customize the directories that are monitored with the directories option.
User Jobs
The UserJobs recorder captures information about the users dispatching jobs in your application.
You may optionally adjust the sample rate and ignored job patterns.
User Requests
The UserRequests recorder captures information about the users making requests to your application.
You may optionally adjust the sample rate and ignored URL patterns.
Filtering
As we have seen, many recorders offer the ability to, via configuration, "ignore" incoming entries based on their value, such as a request's URL. But, sometimes it may be useful to filter out records based on other factors, such as the currently authenticated user. To filter out these records, you may pass a closure to Pulse's filter method. Typically, the filter method should be invoked within the boot method of your application's AppServiceProvider:
import { Auth } from '@laraflare/framework';
import { Entry, Pulse, Value } from '@laraflare/pulse';
/**
* Bootstrap any application services.
*/
override boot(): void {
Pulse.filter((entry: Entry | Value) => {
return Auth.user().isNotAdmin();
});
// ...
}
Performance
Pulse has been designed to drop into an existing application without requiring any additional infrastructure. However, for high-traffic applications, there are several ways of removing any impact Pulse may have on your application's performance.
Using a Different Database
For high-traffic applications, you may prefer to use a dedicated database connection for Pulse to avoid impacting your application database.
You may customize the database connection used by Pulse by setting the PULSE_DB_CONNECTION environment variable.
PULSE_DB_CONNECTION=pulse
Redis Ingest
Warning
The Redis Ingest requires Redis 6.2 or greater.
By default, Pulse will store entries directly to the configured database connection after the response has been sent to the client or a job has been processed; however, you may use Pulse's Redis ingest driver to send entries to a Redis stream instead. This can be enabled by configuring the PULSE_INGEST_DRIVER environment variable:
PULSE_INGEST_DRIVER=redis
Pulse will use your default Redis connection by default, but you may customize this via the PULSE_REDIS_CONNECTION environment variable:
PULSE_REDIS_CONNECTION=pulse
Warning
When using the Redis ingest driver, your Pulse installation should always use a different Redis connection than your Redis powered queue, if applicable.
When using the Redis ingest, you will need to run the pulse:work command to monitor the stream and move entries from Redis into Pulse's database tables.
npx artisan pulse:work
Note
To keep the
pulse:workprocess running permanently in the background, you should use a process monitor to ensure that the Pulse worker does not stop running.
As the pulse:work command is a long-lived process, it will not see changes to your codebase without being restarted. You should gracefully restart the command by calling the pulse:restart command during your application's deployment process:
npx artisan pulse:restart
Note
Pulse uses the cache to store restart signals, so you should verify that a cache driver is properly configured for your application before using this feature.
Sampling
By default, Pulse will capture every relevant event that occurs in your application. For high-traffic applications, this can result in needing to aggregate millions of database rows, especially for longer time periods.
You may instead choose to enable "sampling" on certain Pulse data recorders. For example, setting the sample rate to 0.1 on the User Requests recorder will mean that you only record approximately 10% of the requests to your application. The aggregated values will be scaled up to approximate the whole.
In general, the more entries you have for a particular metric, the lower you can safely set the sample rate without sacrificing too much accuracy.
Trimming
Pulse will automatically trim its stored entries once they are outside of the retention window. Trimming occurs when ingesting data using a lottery system which may be customized in the Pulse configuration file.
Handling Pulse Exceptions
If an exception occurs while capturing Pulse data, such as being unable to connect to the storage database, Pulse will silently fail to avoid impacting your application.
If you wish to customize how these exceptions are handled, you may provide a closure to the handleExceptionsUsing method:
import { Log } from '@laraflare/framework';
import { Pulse } from '@laraflare/pulse';
Pulse.handleExceptionsUsing((e: Error) => {
Log.debug('An exception happened in Pulse', {
message: e.message,
stack: e.stack,
});
});
Custom Cards
Pulse's cards are Livewire components rendered with Blade, which laraflare does not have, so there are no card components, card styling or dashboard view to customize. The data side of a custom card, recording and aggregating entries, works as described below, and you may show the result on your own Vue screens.
Data Capture and Aggregation
Capturing Entries
Pulse allows you to record "entries" using the Pulse.record method:
import { Pulse } from '@laraflare/pulse';
Pulse.record('user_sale', user.id, sale.amount)
.sum()
.count();
The first argument provided to the record method is the type for the entry you are recording, while the second argument is the key that determines how the aggregated data should be grouped. For most aggregation methods you will also need to specify a value to be aggregated. In the example above, the value being aggregated is sale.amount. You may then invoke one or more aggregation methods (such as sum) so that Pulse may capture pre-aggregated values into "buckets" for efficient retrieval later.
The available aggregation methods are:
avgcountmaxminsum
Note
When building a package that captures the currently authenticated user ID, you should use the
Pulse.resolveAuthenticatedUserId()method, which respects any user resolver customizations made to the application.
Custom Recorders
Package authors may wish to provide recorder classes to allow users to configure the capturing of data.
Recorders are registered in the recorders section of the application's config/pulse.ts configuration file:
recorders: new Map([
// ...
[Deployments, {
// ...
}],
]),
Recorders may listen to events by specifying a listen property. Pulse will automatically register the listeners and call the recorder's record method:
import { Config } from '@laraflare/framework';
import { Pulse } from '@laraflare/pulse';
import { Deployment } from '../Events/Deployment';
export class Deployments {
/**
* The events to listen for.
*/
listen: Array<typeof Deployment> = [
Deployment,
];
/**
* Record the deployment.
*/
record(event: Deployment): void {
const config = Config.get(`pulse.recorders.${Deployments.name}`);
Pulse.record(
// ...
);
}
}