npm.io
1.0.7 • Published 2d ago

dbpulse-agent

Licence
MIT
Version
1.0.7
Deps
0
Size
42 kB
Vulns
0
Weekly
434

dbpulse-agent

Real-time database query capture for DBPulse

npm version license node

A lightweight, drop-in agent that captures every database query from your Node.js application and streams it to DBPulse for real-time monitoring, slow-query detection, and performance analytics.

Supports MongoDB, PostgreSQL, and MySQL — currently available for MongoDB (all tiers including Atlas Free), with PostgreSQL and MySQL support coming soon.

Getting Started · Supported Databases · API Reference · Desktop App · Configuration


Why dbpulse-agent?

Traditional database monitoring tools often require elevated database permissions, paid tiers, or complex infrastructure. dbpulse-agent takes a different approach — it captures queries at the application layer, so it works everywhere with zero database configuration.

  • Multi-database support — built to work with MongoDB, PostgreSQL, and MySQL. MongoDB support is live today; PostgreSQL and MySQL are coming soon.
  • Application-layer capture — hooks directly into your ORM/driver, so it works on every database tier — including MongoDB Atlas Free (M0/M2/M5) where the profiler and $currentOp are unavailable.
  • Near-zero overhead — logs are batched in memory and flushed asynchronously; your query performance stays untouched.
  • Request correlation — automatically links each database query to the HTTP request that triggered it using AsyncLocalStorage.
  • Drop-in setup — two lines of code and an Express middleware. No schema changes, no agents to deploy on your database server.
  • Privacy-conscious — captures query filters and timing, not your actual data.

Prerequisites

Requirement Version
Node.js >= 18.0.0
Mongoose >= 6.0.0 (for MongoDB)
DBPulse account Sign up to get your API key and connection ID

dbpulse-agent currently supports MongoDB (via Mongoose) in Node.js. Support for PostgreSQL and MySQL is actively being developed and will be available soon — see Supported Databases.


Getting Started

1. Install
npm install dbpulse-agent
2. Initialize the agent

Add this at the very top of your server entry file — before mongoose.connect() and before any Mongoose model imports:

import { DBPulseAgent } from "dbpulse-agent"

DBPulseAgent.init({
  apiKey: "your-api-key",
  connectionId: "your-connection-id",
  debug: true,        // optional: enable console logging (disable in production)
})
3. Add the request tracking middleware

After your Express app initialization, add the tracking middleware to correlate database queries with incoming HTTP requests:

import express from "express"

const app = express()

// Add DBPulse request tracking
app.use(DBPulseAgent.trackRequests())

// ... your routes below

Flush any remaining buffered logs when your server stops:

process.on("SIGTERM", async () => {
  await DBPulseAgent.shutdown()
  process.exit(0)
})

That's it — every Mongoose query will now appear in your DBPulse dashboard. Download the DBPulse Desktop App to view your captured queries in real time.


Complete Example

import { DBPulseAgent } from "dbpulse-agent"
import express from "express"
import mongoose from "mongoose"

// ① Initialize DBPulse FIRST
DBPulseAgent.init({
  apiKey: "your-api-key",
  connectionId: "your-connection-id",
  debug: false
})

// ② Create your Express app
const app = express()
app.use(express.json())

// ③ Add request tracking middleware
app.use(DBPulseAgent.trackRequests())

// ④ Define routes and models as usual
const User = mongoose.model("User", new mongoose.Schema({ name: String }))

app.get("/users", async (req, res) => {
  const users = await User.find()  // ← automatically captured by DBPulse
  res.json(users)
})

// ⑤ Connect to MongoDB and start
await mongoose.connect(process.env.MONGO_URI)
app.listen(3000, () => console.log("Server running on port 3000"))

// ⑥ Graceful shutdown
process.on("SIGTERM", async () => {
  await DBPulseAgent.shutdown()
  process.exit(0)
})

API Reference

DBPulseAgent.init(options)

Initializes the agent. Must be called once, before mongoose.connect().

Parameter Type Required Default Description
apiKey string Your DBPulse API key (from the dashboard)
connectionId string The connection ID from your DBPulse dashboard
debug boolean false Enables verbose console logging
flushIntervalMs number 2000 How often (in ms) buffered logs are sent to the backend
DBPulseAgent.trackRequests()

Returns an Express-compatible middleware function. Wraps each incoming request in an AsyncLocalStorage context so that all database queries triggered during that request are automatically tagged with:

  • Route path — e.g. /api/users/:id
  • HTTP method — e.g. GET, POST
  • Request ID — a unique UUID per request
app.use(DBPulseAgent.trackRequests())
DBPulseAgent.flush()

Manually flushes the in-memory log buffer to the DBPulse backend. Useful for testing or before a graceful shutdown.

await DBPulseAgent.flush()
DBPulseAgent.shutdown()

Flushes remaining logs, clears all timers, and resets the agent. Call this during server shutdown.

await DBPulseAgent.shutdown()

Configuration

Flush Interval

The agent batches captured queries and sends them at a configurable interval (default: 2 seconds). Adjust based on your needs:

DBPulseAgent.init({
  // ...
  flushIntervalMs: 5000, // send every 5 seconds (lower network overhead)
})

Security

  • No plaintext secrets — DBPulse encrypts all connection URIs locally using your operating system's native keychain before storing anything on disk.
  • In-memory only — secrets are decrypted only in memory when needed and never written to logs or temp files.
  • Instant revocation — deleting a connection from the dashboard immediately removes all associated encrypted data.
  • Query filters only — the agent captures query shapes and filters ({ status: "active" }), not your actual document data.

Supported Databases

DBPulse is designed to work across multiple databases. Here's the current support status:

Database Status Runtime Details
MongoDB Available Node.js (Mongoose >=6) Full query, aggregation, and save capture. Works on all tiers — Atlas Free (M0/M2/M5), Dedicated (M10+), and self-hosted.
PostgreSQL Coming soon Node.js Requires pg_monitor role — GRANT pg_monitor TO your_user;. For RDS/Aurora, ensure rds_superuser is assigned.
MySQL Coming soon Node.js Requires PROCESS privilege — GRANT PROCESS ON *.* TO 'user'@'host';. For managed MySQL (RDS, PlanetScale), ensure the PROCESS admin privilege is granted.
Planned Integrations
Integration Status Description
Native MongoDB driver Planned Capture queries without Mongoose
Prisma adapter Planned Prisma middleware integration
Drizzle ORM Planned Drizzle query logging

Want to see a specific database or ORM supported sooner? Open an issue and let us know!


Captured Query Data

Each captured log entry includes:

{
  "connectionId": "6a15564e6e545a11...",
  "dbType": "mongodb",
  "collection": "users",
  "method": "find",
  "query": { "status": "active" },
  "durationMs": 12,
  "routePath": "/api/users",
  "routeMethod": "GET",
  "requestId": "a3f1c2d4-...",
  "capturedAt": "2026-06-15T10:30:00.000Z"
}
Field Description
collection The database collection / table name
method Database operation — find, findOne, updateOne, deleteMany, aggregate, save, etc.
query The query filter or aggregation pipeline
durationMs Execution time in milliseconds
routePath The HTTP route that triggered the query (requires middleware)
routeMethod The HTTP method (GET, POST, etc.)
requestId Unique ID linking all queries from a single HTTP request

FAQ

Does this work on MongoDB Atlas Free Tier (M0)?
Yes! That's one of the main reasons dbpulse-agent exists. Since the agent captures queries at the application layer (not the database layer), it works on all MongoDB tiers — including M0, M2, and M5 shared clusters where the profiler and $currentOp are unavailable.
Will this slow down my queries?
No. The agent adds a Date.now() call before and after each query (sub-microsecond overhead) and pushes a small object to an in-memory array. Logs are flushed asynchronously on a timer — your query execution path is never blocked by network I/O.
Do I need the Express middleware?
The middleware is optional but recommended. Without it, queries are still captured, but they won't have routePath, routeMethod, or requestId metadata. If you're using a framework other than Express, you can manually create a context using the AsyncLocalStorage API.
What happens if the DBPulse backend is unreachable?
Logs are kept in the in-memory buffer and retried on the next flush cycle. Your application continues running normally — network failures never throw errors into your application code.
Can I use this without Mongoose?
Not yet. The current version hooks into Mongoose's query prototype. Native MongoDB driver support is on the roadmap.

DBPulse Desktop App

To view and analyze the queries captured by dbpulse-agent, download the DBPulse Desktop App — available for Windows, macOS, and Linux.

Platform Download
Windows Download for Windows
macOS Download for macOS
Linux Download for Linux

The desktop app lets you:

  • View all captured queries in real time
  • Identify slow queries and performance bottlenecks
  • Filter by collection, method, route, environment, and more
  • Track query performance trends over time
  • Trace queries back to the exact HTTP request that triggered them

Visit the DBPulse website to learn more and create your free account


License

MIT DBPulse

Keywords