Transactions and Segments

A transaction is one logical unit of work: an inbound web request or a background job. A segment is a timed piece of work inside a transaction (a database query, an external call, a function you choose to time). Instrumented servers create web transactions automatically; this page covers the API for naming them, creating your own, and timing code inside them.

setTransactionName(name)

Gives the current transaction a custom name, overriding the framework's route-based name and any naming rules (local or from the server).

Parameter Type Description
name string The name. It is reported with the prefix Custom/.

Returns: undefined.

app.post('/api/v2/*', (req, res) => {
  newrelic.setTransactionName('api-v2-catchall')
  res.send('ok')
})

Notes:

  • Must be called while a transaction is active; otherwise it logs No transaction found when setting name to '<name>'.
  • An empty name logs Must include name in setTransactionName call for URL <url>. and changes nothing.
  • The last call wins. Use low-cardinality names: names containing IDs or timestamps create too many metrics (a "metric grouping issue").

setControllerName(name, action)

Names the current transaction after a controller and action, as Controller/<name>/<action>. Overrides naming rules like setTransactionName.

Parameter Type Description
name string Controller name.
action string Optional. Defaults to the request's HTTP method (transaction.verb), or GET if unknown.
newrelic.setControllerName('users', 'show') // Controller/users/show
newrelic.setControllerName('users')         // Controller/users/GET for a GET request

The same "no transaction" and "missing name" rules apply as for setTransactionName.

getTransaction()

Returns a handle to the current transaction. Use it to end a transaction yourself, to ignore it, or to propagate distributed trace headers manually.

Returns: a TransactionHandle. Outside a transaction, a stub handle whose methods only log at debug level.

Handle method Description
end([callback]) Ends the transaction. The optional callback is called asynchronously (setImmediate) with the transaction.
ignore() Marks the transaction to be ignored: no data is sent for it.
isSampled() Whether the transaction is sampled for distributed tracing.
acceptDistributedTraceHeaders(transportType, headers) Accept incoming trace context. See Tracing and Browser.
insertDistributedTraceHeaders(headers) Add outgoing trace context to a headers object.

Warning: Calling getTransaction() marks the transaction as handled externally. A transaction created by startWebTransaction or startBackgroundTransaction whose handler returns a non-promise value will then not end automatically — you must call handle.end(). Forgetting this leaves the transaction open.

newrelic.startBackgroundTransaction('import', 'Jobs', function () {
  const tx = newrelic.getTransaction()
  importer.run((err) => {
    if (err) newrelic.noticeError(err)
    tx.end()
  })
})

startWebTransaction(url, handle)

Creates a web transaction around handle, for request-like work the agent does not see automatically (a custom protocol server, a WebSocket message handler).

Parameter Type Description
url string Name of the transaction (used like a URL, and passed through your naming rules). Use a generic value without variable parts.
handle function The work. Called with no arguments.

Returns: the return value of handle, or null if handle is not a function.

When the transaction ends

  1. If handle returns a promise, the transaction ends when the promise settles.
  2. Otherwise, if getTransaction() was called inside handle, it ends when you call end() on the handle.
  3. Otherwise it ends as soon as handle returns synchronously — asynchronous callbacks scheduled inside will run outside the timing.
ws.on('message', (msg) => {
  newrelic.startWebTransaction('/ws/message', async () => {
    await handleMessage(msg)
  })
})

Edge cases from the source:

  • With an empty url, it logs startWebTransaction called without a url, transaction not started and simply calls handle().
  • If already inside a web transaction, no nested transaction is created: the work is recorded as a segment named url in the existing transaction. Inside a background transaction, a new web transaction is created.
  • If the agent cannot collect data yet or anymore (for example it is stopped), handle runs without a transaction.

startBackgroundTransaction(name, group, handle)

Creates a non-web (background) transaction around handle — for queue consumers, timers, cron jobs, CLI scripts.

Parameter Type Description
name string Transaction name. Keep it generic.
group string Optional. Grouping in the APM UI. Defaults to Nodejs.
handle function The work.

The transaction is named <group>/<name> (for example Jobs/cleanup). The end rules are the same as for startWebTransaction.

// Two-argument form: group defaults to "Nodejs"
newrelic.startBackgroundTransaction('nightly-report', () => buildReport())

// Three-argument form
consumer.on('message', (m) =>
  newrelic.startBackgroundTransaction('order-created', 'Queue', () => process(m))
)

Nested calls inside an existing background transaction become segments, not new transactions. An empty name logs startBackgroundTransaction called without a name and runs handle() untracked.

endTransaction()

Ends the transaction in the current context. For a web transaction it also finalizes the name. Outside a transaction it logs at debug level and does nothing. This is an alternative to getTransaction().end() when you are still in the right async context.

startSegment(name, record, handler, callback)

Times handler as a segment of the current transaction.

Parameter Type Description
name string Segment name, also the metric name when recorded.
record boolean When true, the segment also produces a custom metric shown in the transaction breakdown; when false, it only appears in traces.
handler function The code to time. It receives callback as its argument.
callback function Optional. If given, the segment ends when the callback is called.

Returns: the return value of handler.

The segment ends:

  • when callback is called, if a callback was passed;
  • otherwise when the promise returned by handler settles;
  • otherwise when handler returns.
// Promise-based
const data = await newrelic.startSegment('loadCatalog', true, async () => {
  return fetchCatalog()
})

// Callback-based
newrelic.startSegment('legacyLookup', false, (done) => {
  legacy.lookup(id, done)
}, (err, value) => {
  // the segment has ended here
})

Edge cases:

  • Without a name or a function handler, it logs Name and handler function are both required for startSegment and calls handler(callback) if possible.
  • A callback that is not a function logs If using callback, it must be a function and runs handler untimed.
  • Outside a transaction, handler(callback) runs untimed.

ignoreApdex()

Excludes the current transaction from the Apdex score, for example very long downloads or streaming responses that would otherwise look "frustrating". Outside a transaction it logs Apdex will not be ignored. ignoreApdex must be called within the scope of a transaction.

addNamingRule(pattern, name)

Adds a rule: when a transaction's URL matches pattern, the transaction is named name. Capture groups can be used as $1, $2 in name.

Parameter Type Description
pattern RegExp or string A JavaScript regular expression.
name string Replacement name. A / is prepended internally.
// Good: low-cardinality replacements
newrelic.addNamingRule('^/storefront/(v[1-5])/(item|category|tag)', 'CommerceAPI/$1/$2')

// Bad: one transaction name per item ID
newrelic.addNamingRule('^/item/([0-9a-f]+)', 'Item/$1')

Rules cannot be removed once added. The same rules can be configured with rules.name. A missing name logs Simple naming rules require a replacement name. See Naming Rules.

addIgnoringRule(pattern)

Ignores every transaction whose URL matches pattern (RegExp or string) — useful for health checks and long-polling endpoints that distort response time and Apdex.

newrelic.addIgnoringRule('^/socket\\.io/')
newrelic.addIgnoringRule(/^\/health$/)

Equivalent to adding the pattern to rules.ignore, whose default is ['^/socket.io/.*/xhr-polling/'].

See Also