In this post, I am sharing how to identify a Heroku dynos from within your application.

In many cases, well written cloud applications does not need to know what Heroku dyno is handling a request. However, sometimes that knowledge is essential.

That need has been addressed by Heroku team. The Dyno Manager adds DYNO environment variables that holds identifier of your dyno e.g. web.1, web.2, whatever.1 etc. The variable value can be parsed in order to fetch a counter.

Examples

Node.js

var dynoId = process.env.DYNO;
var id = /\w+\.(\d+)/.exec(dynoId)[1];

Java

final String dynoId = System.getenv("DYNO");
final Matcher matcher = Pattern.compile("(\\w+)\\.(\\d+)").matcher(dynoId);

String id = null;

if(matcher.find()) {
    id = matcher.group(2); // returns index: 1
    // matcher.group(1) - returns name: web
}

For values like web.1 or web.2 the id variable should be "1" or "2" respectively.

Uniqueness

Note that in some rare cases, during a deployment or restart, the same dyno identifier could be used for two running dynos. After a deployment or restart completion, dyno identifier will be consistent.

Please note that the $DYNO variable is still experimental and subject to change or removal.