Skip to content

Enable prisma metrics and add them to the /metrics endpoint #2111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion apps/webapp/app/routes/metrics.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
import { LoaderFunctionArgs } from "@remix-run/server-runtime";
import { prisma } from "~/db.server";
import { metricsRegister } from "~/metrics.server";

export async function loader({ request }: LoaderFunctionArgs) {
return new Response(await metricsRegister.metrics(), {
// If the TRIGGER_METRICS_AUTH_PASSWORD is set, we need to check if the request has the correct password in auth header
const authPassword = process.env.TRIGGER_METRICS_AUTH_PASSWORD;

if (authPassword) {
const auth = request.headers.get("Authorization");
if (auth !== `Bearer ${authPassword}`) {
return new Response("Unauthorized", { status: 401 });
}
}

const prismaMetrics = await prisma.$metrics.prometheus();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for the Prisma metrics call.

The call to prisma.$metrics.prometheus() could potentially fail, which would cause the entire metrics endpoint to fail. Consider adding error handling to gracefully degrade when Prisma metrics are unavailable.

-  const prismaMetrics = await prisma.$metrics.prometheus();
+  let prismaMetrics = "";
+  try {
+    prismaMetrics = await prisma.$metrics.prometheus();
+  } catch (error) {
+    console.error("Failed to fetch Prisma metrics:", error);
+    // Continue with empty prisma metrics to avoid breaking the endpoint
+  }
🤖 Prompt for AI Agents
In apps/webapp/app/routes/metrics.ts at line 6, the call to
prisma.$metrics.prometheus() lacks error handling, which can cause the metrics
endpoint to fail if the call throws an error. Wrap this call in a try-catch
block to catch any exceptions, and in the catch block, handle the error
gracefully by either returning a fallback response or logging the error and
returning an empty or default metrics response to ensure the endpoint remains
functional.

const coreMetrics = await metricsRegister.metrics();

return new Response(coreMetrics + prismaMetrics, {
Comment on lines +17 to +19
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify the metrics concatenation approach.

Simple string concatenation of Prometheus metrics may not be the correct approach. Prometheus metrics typically require proper formatting, and there could be conflicts between metric names or improper line endings.

Consider using a proper Prometheus metrics library for combining metrics:

-  return new Response(coreMetrics + prismaMetrics, {
+  // Ensure proper line separation between metric sets
+  const combinedMetrics = [coreMetrics.trim(), prismaMetrics.trim()]
+    .filter(Boolean)
+    .join('\n');
+  
+  return new Response(combinedMetrics, {

🏁 Script executed:

#!/bin/bash
# Description: Search for existing Prometheus metrics handling patterns in the codebase
# Expected: Find examples of how metrics are properly combined or formatted

# Search for other prometheus metrics usage
rg -A 5 -B 5 "prometheus|metrics" --type typescript --type javascript

# Look for existing metrics formatting or combination logic
ast-grep --pattern 'metricsRegister.$_($$$)'

Length of output: 244


🏁 Script executed:

#!/bin/bash
# Locate prismaMetrics usage and display the metrics route implementation
grep -n "prismaMetrics" apps/webapp/app/routes/metrics.ts || true
sed -n '1,200p' apps/webapp/app/routes/metrics.ts

Length of output: 693


Ensure proper Prometheus metrics formatting when combining outputs

Directly concatenating two metrics strings can lead to missing newline separators or duplicated HELP/TYPE directives, which breaks the Prometheus exposition format. It’s safer to trim each output and join them with a newline.

• File: apps/webapp/app/routes/metrics.ts
Update the loader’s return to combine and format both metric strings.

Suggested diff:

   const prismaMetrics = await prisma.$metrics.prometheus();
   const coreMetrics = await metricsRegister.metrics();
-
-  return new Response(coreMetrics + prismaMetrics, {
+  // Combine metrics outputs with proper newline separation
+  const combinedMetrics = [coreMetrics.trim(), prismaMetrics.trim()]
+    .filter(Boolean)
+    .join('\n');
+
+  return new Response(combinedMetrics, {
     headers: {
       "Content-Type": metricsRegister.contentType,
     },
   });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const coreMetrics = await metricsRegister.metrics();
return new Response(coreMetrics + prismaMetrics, {
const prismaMetrics = await prisma.$metrics.prometheus();
const coreMetrics = await metricsRegister.metrics();
// Combine metrics outputs with proper newline separation
const combinedMetrics = [coreMetrics.trim(), prismaMetrics.trim()]
.filter(Boolean)
.join('\n');
return new Response(combinedMetrics, {
headers: {
"Content-Type": metricsRegister.contentType,
},
});
🤖 Prompt for AI Agents
In apps/webapp/app/routes/metrics.ts around lines 7 to 9, the code concatenates
Prometheus metrics strings directly, which can cause formatting issues such as
missing newlines or duplicated HELP/TYPE directives. To fix this, trim both
metrics strings individually and join them with a single newline character
before returning the combined response, ensuring proper Prometheus exposition
format.

headers: {
"Content-Type": metricsRegister.contentType,
},
Expand Down
2 changes: 1 addition & 1 deletion internal-packages/database/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ datasource db {
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "debian-openssl-1.1.x"]
previewFeatures = ["tracing"]
previewFeatures = ["tracing", "metrics"]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify the stability of the Prisma metrics preview feature.

Adding the "metrics" preview feature enables Prisma client metrics collection. Since preview features can have breaking changes and may not be production-ready, ensure this feature is stable enough for your use case.


🌐 Web query:

What is the current status and stability of Prisma's "metrics" preview feature? Is it production-ready?

💡 Result:

As of May 2025, Prisma has announced plans to discontinue the "metrics" preview feature between June and August 2025 due to low usage and compatibility issues with the Query Compiler. (github.com) Consequently, the "metrics" feature is not considered production-ready.

For monitoring and observability, Prisma recommends using the "tracing" feature, which provides detailed insights into database interactions and is fully supported. (prismagraphql.com)

Citations:


Remove the “metrics” preview feature – it’s unstable and slated for removal

Prisma has announced that the “metrics” preview feature will be discontinued between June and August 2025 and is not production-ready. To avoid future breakages, remove it from your schema and rely on the fully supported “tracing” feature for observability.

Please update:

  • internal-packages/database/prisma/schema.prisma (line 10)
- previewFeatures = ["tracing", "metrics"]
+ previewFeatures = ["tracing"]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
previewFeatures = ["tracing", "metrics"]
previewFeatures = ["tracing"]
🤖 Prompt for AI Agents
In internal-packages/database/prisma/schema.prisma at line 10, remove the
"metrics" entry from the previewFeatures array because it is an unstable Prisma
preview feature slated for removal. Keep only the "tracing" feature to ensure
stability and avoid future breakages related to the deprecated "metrics"
feature.

}

model User {
Expand Down
Loading