RudderStack Java SDK Reference

Complete Java SDK API reference for tracking and sending server-side events from your Java applications.

RudderStack’s Java SDK provides a comprehensive API for tracking and sending events from your Java applications to various destinations.

For implementation examples and source code, see the SDK’s GitHub repository.

Prerequisites

Installation

RudderStack recommends using the Maven build system to add the Java SDK to your project.

Initialization

To initialize the RudderStack client, use the following code:

RudderAnalytics analytics = RudderAnalytics
         .builder("<WRITE_KEY>")
         .setDataPlaneUrl("<DATA_PLANE_URL>")
         .build();
info
To migrate to the Java SDK v3, set the data plane URL using setDataPlaneUrl("<DATA_PLANE_URL>") instead of passing it as an argument.

Configuration options

The RudderClient.Builder class provides the following configuration methods:

MethodTypeDescriptionDefault value
clientOkHttpClientSets a custom OkHttpClientCreated by default
setGZIPBooleanEnables/disables Gzip compressiontrue
logLogSets logging level (VERBOSE, DEBUG, ERROR, NONE)NONE
setDataPlaneUrlStringSets data plane URLhttps://hosted.rudderlabs.com/

Note: The method automatically appends v1/batch to the URL if not present.
setUploadURLStringSets data plane URL (used for Segment compatibility)https://hosted.rudderlabs.com/v1/batch
userAgentStringSets HTTP request user agentanalytics-java/{version}
queueCapacityIntegerSets queue capacityInteger.MAX_VALUE
retriesIntegerSets maximum event retries3
networkExecutorExecutorServiceSets executor service for HTTP requestsSingleThreadExecutor
callbackCallbackInvoked on event processingEmpty list
forceTlsVersion1BooleanEnforces TLS v1false

Beta configuration options

warning
The following methods are currently in beta and subject to change.
MethodTypeDescriptionDefault value
messageTransformerMessageTransformerTransforms message before uploadnull
messageInterceptorMessageInterceptorIntercepts messagesnull
flushQueueSizeIntegerQueue size triggering flush250
maximumQueueSizeInBytesIntegerMaximum queue size for flush1024*500 Bytes
flushIntervalLong, TimeUnitQueue flush interval10 seconds
threadFactoryThreadFactoryThread factory for creationnull
pluginPluginBuilder configurationnull

Event methods

warning
The Java SDK does not persist user state. You must specify either userId or anonymousId with every event API call.

Identify

The identify method records user identity and traits.

Example:

analytics.enqueue(IdentifyMessage.builder()
    .userId("1hKOmRA4GRlm")
    .traits(ImmutableMap.builder()
        .put("name", "Alex Keener")
        .put("email", "alex@example.com")
        .put("plan", "enterprise")
        .put("logins", 24)
        .build()
    )
);

Parameters:

FieldTypeDescription
userId
Required, if anonymousId is absent.
StringUnique identifier for a user in your database.
anonymousId
Required, if userId is absent.
StringIdentifier set in cases where no unique user identifier is available.
traitsObjectDictionary of the user’s traits like name, email, etc.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampTimestamp in ISO 8601 formatThe event’s timestamp. If not provided, it defaults to the current time when the message was built.

Track

The track method records user actions and their associated properties.

Example:

// Create a map to store event properties
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("product_id", "P123");
properties.put("product_name", "Running Shoes");
properties.put("price", 89.99);
properties.put("currency", "USD");
properties.put("category", "Sports");

// Send the track event
analytics.enqueue(
   TrackMessage.builder("Product Added")
       .properties(properties)
       .userId("1hKOmRA4GRlm")
);

Parameters:

FieldTypeDescription
userId
Required, if anonymousId is absent.
StringUnique identifier for a user in your database.
anonymousId
Required, if userId is absent.
StringIdentifier set in cases where no unique user identifier is available.
event
Required
StringName of the event.
propertiesObjectOptional dictionary of the properties associated with the event.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampDateThe event’s timestamp. If not provided, it defaults to the current time when the message is created. The SDK automatically converts it in the ISO 8601 format before sending to the server.

Page

The page call records page views in your application along with the relevant page information.

Example:

analytics.enqueue(PageMessage.builder("Schedule")
    .userId("1hKOmRA4GRlm")
    .properties(ImmutableMap.builder()
        .put("category", "Cultural")
        .put("path", "/a/b")
        .build()
    )
);

Parameters:

FieldTypeDescription
userId
Required, if anonymousId is absent.
StringUnique identifier for a user in your database.
anonymousId
Required, if userId is absent.
StringIdentifier set in cases where no unique user identifier is available.
name
Required
StringName of the viewed page.
propertiesObjectOptional dictionary of the properties associated with the viewed page, like url or referrer.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampTimestamp in ISO 8601 formatThe event’s timestamp. If not provided, it defaults to the current time when the message was built.

Screen

The screen call records screen views in your mobile app.

Example:

analytics.enqueue(ScreenMessage.builder("Product List")
    .userId("1hKOmRA4GRlm")
    .properties(ImmutableMap.builder()
        .put("category", "Sports")
        .put("path", "/products/sports")
        .put("view_type", "grid")
        .put("filters_applied", true)
        .build()
    )
);

Parameters:

FieldTypeDescription
userId
Required, if anonymousId is absent.
StringUnique identifier for a user in your database.
anonymousId
Required, if userId is absent.
StringIdentifier set in cases where no unique user identifier is available.
name
Required
StringName of the viewed screen.
propertiesObjectOptional dictionary of the properties associated with the screen, like url or referrer.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampTimestamp in ISO 8601 formatThe event’s timestamp. If not provided, it defaults to the current time when the message was built.

Group

The group call links an identified user with a group and records any custom traits associated with that group.

Example:

analytics.enqueue(GroupMessage.builder("org_123")
    .userId("1hKOmRA4GRlm")
    .traits(ImmutableMap.builder()
        .put("name", "Acme Corp")
        .put("industry", "Technology")
        .put("employees", 500)
        .put("plan", "enterprise")
        .build()
    )
);

Parameters:

FieldTypeDescription
userId
Required, if anonymousId is absent.
StringUnique identifier for a user in your database.
anonymousId
Required, if userId is absent.
StringIdentifier set in cases where no unique user identifier is available.
groupId
Required
StringUnique identifier for the group in your database.
traitsObjectDictionary of the group’s traits like nameor email.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampTimestamp in ISO 8601 formatThe event’s timestamp. If not provided, it defaults to the current time when the message was built.

Alias

warning
RudderStack supports sending alias events only to some destinations. See the destination-specific documentation for more information.

The alias call merges different identities of a known user.

Example:

analytics.enqueue(AliasMessage.builder("old_user_123")
    .userId("new_user_456")
);

Parameters:

FieldTypeDescription
userId
Required, if anonymousId is absent.
StringUnique identifier for a user in your database.
anonymousId
Required, if userId is absent.
StringIdentifier set in cases where no unique user identifier is available.
previousId
Required
StringPrevious identifier for the user.
traitsObjectOptional dictionary of the user’s traits like name or email.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampTimestamp in ISO 8601 formatThe event’s timestamp. If not provided, it defaults to the current time when the message was built.

Context object

The context object in the Java SDK provides additional information about the event:

analytics.enqueue(TrackMessage.builder("Order Completed")
    .userId("1hKOmRA4GRlm")
    .context(ImmutableMap.builder()
        .put("ip", "203.0.113.9")
        .put("locale", "en-US")
        .put("userAgent", "Mozilla/5.0")
        .put("timezone", "America/New_York")
        .build()
    )
);

The SDK automatically adds the following library information to every message:

"context": {
    "library": {
        "name": "analytics-java",
        "version": "x.x.x"
    }
}

Any custom information passed in the context object is merged with the existing context, except for the library information.

Destination filtering

The SDK provides methods to enable or disable sending events to specific destinations by passing the integrations object in your API calls:

analytics.enqueue(TrackMessage.builder("Order Completed")
    .userId("1hKOmRA4GRlm")
    .enableIntegration("All", false)  // Disable all destinations
    .enableIntegration("Amplitude", true)  // Enable only Amplitude
    .properties(ImmutableMap.builder()
        .put("revenue", 99.99)
        .put("currency", "USD")
        .build()
    )
);
warning
Destination flags are case-sensitive and must match the destination names in the RudderStack dashboard.

Event batching

The SDK queues events in memory and flushes them in batches for optimal performance. Each SDK API call adds the event to the queue instead of making an immediate HTTP request.

Batch size limits

  • Maximum batch request size: 500KB
  • Maximum single event size: 32KB
warning
The RudderStack HTTP Tracking API accepts batch requests up to 500KB. Keep single event payloads below 32KB to avoid errors.

Event flushing

The Java SDK provides a flush method that notifies the RudderStack client to upload the events and make sure no events are left in the queue at any given point.

Manual flush

The flush method usage is shown below:

analytics.flush()

Flush blocking

By default, the Java SDK does not support blocking event flush implicitly. However, you can implement it using the following two classes:

  • BlockingFlush: Handles up to 65535 parallel flush calls
  • TierBlockingFlush: No limit on parallel flush calls
warning
Both the BlockingFlush and TierBlockingFlush classes are not included in the core SDK.

BlockingFlush implementation

TierBlockingFlush implementation

Event request compression

info

Note the following:

  • The event request compression feature via Gzip is enabled by default in the Java SDK version 3.0.0.
  • Self-hosted data planes require rudder-server version 1.4+ to support event request compression.

The Java SDK automatically gzips event requests by leveraging interceptors in OkHttp.

When using a custom OkHttp client with the client API, its interceptor configuration takes precedence over the setGZIP setting.

See the sample application for a working example.

Disable compression

RudderAnalytics analytics = RudderAnalytics
         .builder("<WRITE_KEY>")
         .setDataPlaneUrl("<DATA_PLANE_URL>")
         .setGZIP(false)
         .build();

Logging

The SDK provides verbose logging for debugging. You can find the following resources in the SDK’s GitHub repository:

FAQ

Can I use the ImmutableMap class?

Yes, you can use the ImmutableMap class via the Guava library or use the standard Java maps.

Does the Java SDK support event ordering?

The Java SDK does not support event ordering by default.

How does the Java SDK handle events larger than 32KB?

Events larger than 32KB are sent as individual batches to the backend.



Questions? Contact us by email or on Slack