Design Hosted Logs for Node.js & PostgreSQL Rollbacks
In this article
This guide explains how to design hosted log structures that make it easy to understand and execute rollbacks for a Node.js API backed by PostgreSQL. You'll learn what to log before, during, and after a rollback, how to format those logs for clarity, and how to store them in a hosted logging service so you can quickly diagnose failures and reverse bad changes.
What You'll Need
- A Node.js API project connected to PostgreSQL (using an ORM like Sequelize, Knex, or raw
pg). - A hosted logging service (e.g., Logtail, Papertrail, Datadog, or AWS CloudWatch) with an ingestion token or endpoint.
- Basic familiarity with structured logging (JSON logs) and environment variables.
Step-by-Step
- Define a rollback event schema. Create a consistent JSON structure for every rollback-related log. At minimum, include:
event(e.g., "rollback_started", "rollback_completed", "rollback_failed"),transaction_id(a unique ID for the rollback operation),api_version,service(e.g., "user-service"),timestamp(ISO 8601), anddetails(an object for context). Example:{ "event": "rollback_started", "transaction_id": "abc123", "service": "payment-api", "timestamp": "2025-01-01T12:00:00Z" } - Log before executing a rollback. When a rollback is triggered (manually or automatically), log an
eventofrollback_startedwith the reason, the affected migration or deployment ID, and the current database schema version. This gives you a baseline to compare against later. - Log each step of the rollback. If your rollback involves multiple operations (e.g., reverting a migration, restoring a table, or re-running a seed), log each step with a
stepfield (e.g., "migration_revert") and a status (successorfailure). Use the sametransaction_idacross all steps so you can group them in your logging service. - Log the outcome. After the rollback finishes, log
rollback_completedwith the final schema version and a summary of changes. If it fails, logrollback_failedwith the error stack, the step that failed, and any partial changes that were applied. - Add context for PostgreSQL-specific details. Include the database name, schema name, and the affected table(s) in the
detailsobject. If you're using transactions, log the transaction isolation level and whether the rollback was initiated by a caught exception or a manual command. - Send logs to your hosted service. Use a logging library like
pinoorwinstonwith a transport that forwards JSON logs to your hosted endpoint. Set the log level toinfofor normal rollbacks anderrorfor failures. Ensure the service name and environment (e.g.,production) are included in every log entry. - Create a dashboard or query. In your hosted logging service, create a saved query that filters for
event: rollback_*and groups bytransaction_id. This lets you see the full lifecycle of any rollback at a glance. - Test the logging flow. Trigger a test rollback in a staging environment and verify that all logs appear in your hosted service with the correct structure. Check that the
transaction_idis consistent and that you can reconstruct the sequence of events.
Common Mistakes
- Logging without a transaction ID. Without a unique ID, you can't correlate log entries for a single rollback, making debugging nearly impossible.
- Using inconsistent field names. Mixing
eventandeventTypeacross services breaks queries and dashboards. Stick to one schema. - Not logging the rollback reason. If you don't record why the rollback happened, future you won't know if it was a bad deploy or a data corruption issue.
- Ignoring partial failures. If a rollback fails halfway, you must log which steps succeeded and which failed. Otherwise, you can't assess the database state.
- Logging sensitive data. Avoid logging SQL queries that contain user data or credentials. Log table names and operation types instead.
Tips
- Use structured logging from day one. JSON logs are easier to search and parse than plain text. Pino is a fast, low-overhead choice for Node.js.
- Include a correlation ID for the entire API request. Even if a rollback is triggered by a background job, add the request ID that initiated it to the log context.
- Set up alerts. In your hosted logging service, create an alert for
rollback_failedevents so your team is notified immediately. - Log the duration. Record the time taken for each rollback step. This helps you spot slow operations that might indicate locking issues.
- Version your log schema. If you change the structure later, add a
schema_versionfield so old logs remain interpretable.
Troubleshooting
Logs not appearing in the hosted service. First, check that your Node.js process is sending logs to the correct endpoint and that your API key/token is valid. Verify that the log level is set to allow info and error (some libraries default to warn). Also check the network: if your API is behind a firewall, ensure outbound traffic to the logging service is allowed.
Logs are malformed or missing fields. If your logging service shows empty or truncated JSON, your logger might be truncating long messages. Increase the maximum log size in your logger config. Also, double-check that you're using the same field names in every log call — a typo like transacton_id will break grouping.
Can't correlate rollback steps. If you see logs but they lack a common transaction_id, the ID is probably being generated inside a function that runs multiple times. Generate the ID once at the start of the rollback and pass it through the entire process.
Logs are too verbose. If you're logging every SQL query, your log volume may be overwhelming. Filter to only rollback-related events, or use a separate logger instance for rollback operations.
Rollback fails but no error log appears. This often happens when the error is caught and swallowed. Make sure your catch block logs the error with log.error({ event: 'rollback_failed', error: err.stack, ... }) before rethrowing or exiting.
Frequently Asked Questions
Should I log rollbacks in the same log stream as normal API requests?
Yes, but add a distinguishing field like event so you can filter. Keeping everything in one stream simplifies infrastructure.
What if my rollback is manual (via a script)?
Use the same logging schema in your script. The only difference is you won't have an API request ID, so generate a unique transaction_id at the start.
How long should I keep rollback logs?
Longer than your regular logs — at least 30 days, but check your compliance requirements. Rollbacks are rare, so they don't consume much storage.
Can I log rollbacks without a hosted service?
Yes, but you lose central search and alerting. A hosted service is recommended for production, but you can use local JSON files for development.
Do I need to log the actual SQL statements?
No, and it's often unsafe. Log the migration name, table names, and operation type instead. If you need SQL for debugging, log it at debug level and scrub sensitive values.
What's the best way to test the logging setup?
Create a dummy rollback that intentionally fails and verify that the failure log appears with the correct error message. Also test a successful rollback to ensure the completion event is logged.