Java

This is an optional library you can install if you're working with server-side Java applications. It uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your web app or other server side application that needs performance.

Installation

The best way to install the PostHog Java SDK is with a build system like Gradle or Maven. This ensures you can easily upgrade to the latest versions.

Look up the latest version in com.posthog.posthog-server.

Gradle

All you need to do is add the posthog-server module to your build.gradle:

build.gradle
dependencies {
implementation 'com.posthog:posthog-server:1.+'
}

Maven

All you need to do is add the posthog-server module to your pom.xml:

pom.xml
<dependency>
<groupId>com.posthog</groupId>
<artifactId>posthog-server</artifactId>
<version>LATEST</version>
</dependency>

Other

See com.posthog.posthog-server in the Maven Central Repository. Clicking on the latest version shows you options for adding dependencies for other build systems.

Setup

Java
import com.posthog.server.PostHog;
import com.posthog.server.PostHogConfig;
import com.posthog.server.PostHogInterface;
class Sample {
private static final String POSTHOG_API_KEY = "<ph_project_api_key>";
private static final String POSTHOG_HOST = "https://us.i.posthog.com";
public static void main(String args[]) {
PostHogConfig config = PostHogConfig
.builder(POSTHOG_API_KEY)
.host(POSTHOG_HOST)
.build();
PostHogInterface postHog = PostHog.with(config);
postHog.close(); // send the last events in queue
}
}

Capturing events

You can send custom events using capture:

Java
postHog.capture("distinct_id_of_the_user", "user_signed_up");

Tip: We recommend using a [object] [verb] format for your event names, where [object] is the entity that the behavior relates to, and [verb] is the behavior itself. For example, project created, user signed up, or invite sent.

Setting event properties

Optionally, you can include additional information with the event by including a properties object:

Java
postHog.capture(
"distinct_id_of_the_user",
"user_signed_up",
PostHogCaptureOptions
.builder()
.property("login_type", "email")
.property("is_free_trial", true)
.build());

Person profiles and properties

The Java SDK captures identified events by default. These create person profiles. To set person properties in these profiles, include them when capturing an event:

Java
postHog.capture(
"distinct_id_of_the_user",
"event_name",
PostHogCaptureOptions
.builder()
.userProperty("name", "Max Hedgehog")
.userPropertySetOnce("initial_url", "/blog")
.build()
);

For more details on the difference between $set and $set_once, see our person properties docs.

To capture anonymous events without person profiles, set the event's $process_person_profile property to false:

Java
postHog.capture(
"distinct_id_of_the_user",
"event_name",
PostHogCaptureOptions
.builder()
.property("$process_person_profile", false)
.build()
);

Alias

Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend.

In this case, you can use alias to assign another distinct ID to the same user.

Java
postHog.alias("distinct_id", "alias_id");

We strongly recommend reading our docs on alias to best understand how to correctly use this method.

Group analytics

Group analytics allows you to associate an event with a group (e.g. teams, organizations, etc.). Read the group analytics guide for more information.

Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more on our pricing page.

To create a group, use the group method. This associates a user with a group and optionally sets properties on the group:

Java
postHog.group(
"user_distinct_id",
"company",
"company_id_in_your_db",
Map.of(
"name", "Acme Corporation",
"industry", "Technology",
"employee_count", 500
)
);

You can also create a group without setting properties:

Java
postHog.group("user_distinct_id", "organization", "org_123");

To associate an event with a group, include the group information when capturing the event:

Java
postHog.capture(
"user_distinct_id",
"some_event",
PostHogCaptureOptions
.builder()
.group("company", "company_id_in_your_db")
.build()
);

Feature flags

PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.

Boolean feature flags

Java
boolean isEnabled = postHog.isFeatureEnabled("user_distinct_id", "use_optimized_query", false);
if (isEnabled) {
// Do something differently for this user
}

Multivariate feature flags

Java
Object flagValue = postHog.getFeatureFlag("user_distinct_id", "recommendation_algorithm", "control");
String algorithm = flagValue instanceof String ? (String) flagValue : "control";
switch (algorithm) {
case "collaborative_filtering":
useCollaborativeFiltering();
break;
case "neural_network":
useNeuralNetwork();
break;
default:
useControlAlgorithm();
}

Feature flag payloads

Java
Object payload = postHog.getFeatureFlagPayload("user_distinct_id", "recommendation_algorithm");
if (payload instanceof Map) {
Map<String, Object> config = (Map<String, Object>) payload;
String modelVersion = config.get("model_version") instanceof String
? (String) config.get("model_version") : "v1.0";
boolean enableFallback = config.get("enable_fallback") instanceof Boolean
? (Boolean) config.get("enable_fallback") : true;
}

Sending $feature_flag_called events

Capturing $feature_flag_called events enable PostHog to know when a flag was accessed by a user and thus provide analytics and insights on the flag. By default, we send these events when:

  1. You call postHog.getFeatureFlag() or postHog.isFeatureEnabled(), AND
  2. It's a new user, or the value of the flag has changed.

Note: Tracking whether it's a new user or if a flag value has changed happens in a local cache. This means that if you reinitialize the PostHog client, the cache resets as well – causing $feature_flag_called events to be sent again when calling getFeatureFlag or isFeatureEnabled. PostHog is built to handle this, and so duplicate $feature_flag_called events won't affect your analytics.

You can control the automatic capture of $feature_flag_called events using the sendFeatureFlagEvent configuration option when initializing PostHog:

Java
PostHogConfig config = PostHogConfig
.builder(POSTHOG_API_KEY)
.host(POSTHOG_HOST)
.sendFeatureFlagEvent(false) // Disable automatic feature flag events
.build();

Local evaluation

While planned, local evaluation of feature flags is not yet supported in the Java SDK. All feature flag evaluations occur remotely via the PostHog API.

Feature flag caching

To improve performance and reduce API calls, the Java SDK caches feature flag results in memory. You can configure the cache behavior when initializing PostHog:

Java
PostHogConfig config = PostHogConfig
.builder(POSTHOG_API_KEY)
.featureFlagCacheSize(1000) // Maximum number of cached flag results (default: 1000)
.featureFlagCacheMaxAgeMs(300000) // Cache expiry in milliseconds (default: 300000 = 5 minutes)
.build();

Configuration options:

  • featureFlagCacheSize: The maximum number of feature flag results to cache in memory (default: 1000)
  • featureFlagCacheMaxAgeMs: The maximum age of a cached feature flag result in milliseconds (default: 300000 or 5 minutes)

Cached results are stored per distinct ID and flag key combination. When a cached result expires or the cache is full, the SDK will fetch fresh results from the PostHog API.

Experiments (A/B tests)

Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:

Java
Object flagValue = postHog.getFeatureFlag("user_distinct_id", "recommendation_algorithm", "control");
String variant = flagValue instanceof String ? (String) flagValue : "control";
if (variant.equals("neural_network")) {
// Do something differently for this user
}

It's also possible to run experiments without using feature flags.

GeoIP properties

The posthog-server library disregards the server IP, does not add the GeoIP properties, and does not use the values for feature flag evaluations.

Serverless environments

By default, the library buffers events before sending them to the /batch endpoint for better performance. This can lead to lost events in serverless environments if the Java process is terminated by the platform before the buffer is fully flushed.

To avoid this, call postHog.flush() after processing every request. This allows postHog.capture() to remain asynchronous for better performance.

Java
postHog.flush();

Shutdown

When you're done using PostHog, make sure to call close() to ensure all events are flushed before your application exits:

Java
postHog.close();

Community questions

Was this page useful?

Questions about this page? or post a community question.