RudderStack Ruby SDK

Use RudderStack’s Ruby SDK to send server-side events from your Ruby applications to various destinations asynchronously.

RudderStack’s Ruby SDK lets you track and send the events from your Ruby applications to the specified destinations asynchronously. This way, you can use the SDK to improve the performance of your application by reducing the time taken to send the data.

warning

This guide covers the recommended asynchronous Ruby SDK.

See this documentation for the synchronous version, which exists for legacy purposes but will be deprecated soon.

Refer to the SDK’s GitHub codebase for the implementation-specific details.

Github Badge

SDK setup requirements

success
The Setup tab in the RudderStack dashboard has the SDK installation snippet containing both the write key and the data plane URL. Use it to integrate the Ruby SDK into your application.

Install Ruby SDK

  1. Add the following line to your application’s Gem file:
gem 'rudder-sdk-ruby'
  1. Run bundle install to install the gem.

Initialize the SDK

To initialize the SDK, create a client instance as shown below:

require 'rudder-sdk-ruby'

analytics = Rudder::Analytics.new(
  write_key: 'WRITE_KEY',
  data_plane_url: 'DATA_PLANE_URL',
  gzip: true
)

Replace the WRITE_KEY and DATA_PLANE_URL values in the above snippet with the actual values obtained above.

SDK configuration options

You can customize Ruby SDK’s behavior by passing the following options during initialization:

FieldData type
Description
write_key
Required
StringYour Ruby source write key.
data_plane_url
Required
StringYour data plane URL.
gzipBooleanEnables Gzip compression for event requests.

Default value: true
sslBooleanUses SSL/TLS for requests.

Default value: true
batch_sizeIntegerDefines the maximum number of events per batch.

Default value: 100
max_queue_sizeIntegerDefines the maximum queue size before dropping events.

Default value: 10000
retriesIntegerDefines the number of retry attempts for failed requests.

Default value: 10
stubBooleanEnables stub mode for testing.

Default value: false
testBooleanEnables test mode to capture events locally.

Default value: nil
on_errorProcError handler callback.

Default value: `proc {
on_error_with_messagesProcError handler with failed messages.

Default value: `proc {
backoff_policyObjectDefines a custom backoff policy for retry attempts.

Default behavior: Exponential backoff
info

The SDK invokes both the on_error and on_error_with_messages callback functions when events cannot be processed or delivered.

Any logging you implement inside these callbacks will not replace the default logging behavior — your custom logs will be in addition to the default logs.

A sample configuration is shown below:

analytics = Rudder::Analytics.new(
  write_key: 'WRITE_KEY',
  data_plane_url: 'DATA_PLANE_URL',
  gzip: true,
  batch_size: 50,
  max_queue_size: 5000,
  retries: 5,
  on_error: proc { |status, error|
    # Log errors
    puts "Error: #{status} - #{error}"
  },
  on_error_with_messages: proc { |status, error, messages|
    # Handle failed messages
    messages.each do |msg|
      # Retry or persist messages
      puts "Failed: #{msg}"
    end
  }
)

Send events

warning
RudderStack does not store or persist the user state in any of the server-side SDKs.

Unlike the client-side SDKs that deal with only a single user at a given time, the server-side SDKs deal with multiple users simultaneously. Therefore, you must specify either the user_id or anonymous_id every time while making any API calls supported by the Ruby SDK.

Identify

The identify call lets you identify a visiting user and associate them to their actions. It also lets you record the traits about them like their name, email address, etc.

A sample identify call made using the Ruby SDK is shown below:

analytics.identify(
  user_id: '1hKOmRA4GRlm',
  traits: {
    email: "alex@example.com",
    createdAt: "2023-07-24T00:00:00Z",
    subscribe: true
  },
  context: { ip: '10.81.20.10' }
)

The identify method parameters are as shown:

FieldData typeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for the user in your database.
anonymous_id
Required, if user_id is absent.
StringUse this field to set an identifier when there is no unique user identifier available.
traitsObjectOptional dictionary of user traits, like name, email, etc.
contextObjectOptional dictionary of contextual information for the event. It is not directly related to the API call.
integrationsObjectOptional dictionary containing the destinations to be either enabled or disabled.
timestampTimestampThe event’s timestamp.

Note: 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 RudderStack.

Track

The track call lets you record user actions along with their associated properties.

A sample track call made using the Ruby SDK is shown below:

analytics.track(
  user_id: '1hKOmRA4GRlm',
  event: 'Product Shipped',
  properties: {
    product_id: 'SKU-123',
    product_name: 'Ruby Complete Reference',
    price: 29.99,
    currency: 'USD',
    category: 'Books'
  }
)

The track method parameters are as described below:

FieldData typeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for the user in your database.
anonymous_id
Required, if user_id is absent.
StringUse this field to set an identifier when there is no unique user identifier available.
event
Required
StringName of the event.
propertiesObjectOptional dictionary of the properties associated with the event.
contextObjectOptional dictionary of contextual information for the event. It is not directly related to the API call.
integrationsObjectOptional dictionary containing the destinations to be either enabled or disabled.
timestampTimestampThe event’s timestamp.

Note: 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 RudderStack.

Page

The page call lets you record page views on your application along with the other relevant information about the page.

A sample page call made using the Ruby SDK is shown below:

analytics.page(
  user_id: '1hKOmRA4GRlm',
  category: 'Food',
  name: 'Pizza',
  properties: {
    URL: 'https://website.com'
  }
)

The page method parameters are as described below:

FieldData typeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for the user in your database.
anonymous_id
Required, if user_id is absent.
StringUse this field to set an identifier when there is no unique user identifier available.
nameStringName of the viewed page.
propertiesObjectOptional dictionary of the properties associated with the viewed page, like url, referrer, etc.
contextObjectOptional dictionary of contextual information for the event. It is not directly related to the API call.
integrationsObjectOptional dictionary containing the destinations to be either enabled or disabled.
timestampTimestampThe event’s timestamp.

Note: 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 RudderStack.

Screen

The screen call is the mobile equivalent of the page call. It lets you record the screen views on your mobile app along with other relevant information about the screen.

A sample screen call is as shown:

analytics.screen(
  user_id: '1hKOmRA4GRlm',
  category: 'Food',
  name: 'Pizza',
  properties: {
    URL: 'https://website.com'
  }
)

The screen method parameters are as described below:

FieldData typeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for the user in your database.
anonymous_id
Required, if user_id is absent.
StringUse this field to set an identifier when there is no unique user identifier available.
name
Required
StringName of the viewed screen.
categoryStringThe screen’s category.
propertiesObjectOptional dictionary of the properties associated with the viewed screen.
integrationsObjectOptional dictionary containing the destinations to be either enabled or disabled.
contextObjectOptional dictionary of contextual information for the event. It is not directly related to the API call.
timestampTimestampThe event’s timestamp.

Note: 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 RudderStack.

Group

The group call lets you link an identified user with a group, like a company, organization, or an account. It also lets you record any custom traits or properties associated with that group.

A sample group call made using the Ruby SDK is shown below:

analytics.group(
  user_id: '1hKOmRA4GRlm',
  group_id: '12',
  traits: {
    name: 'Company',
    description: 'Software'
  }
)

The group method parameters are as follows:

FieldData typeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for the user in your database.
anonymous_id
Required, if user_id is absent.
StringUse this field to set an identifier when there is no unique user identifier available.
group_id
Required
StringUnique identifier of the group in your database.
traitsObjectOptional dictionary of the group’s traits like name, email, etc.
integrationsObjectOptional dictionary containing the destinations to be either enabled or disabled.
contextObjectOptional dictionary of contextual information for the event. It is not directly related to the API call.
timestampTimestampThe event’s timestamp.

Note: 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 RudderStack.

Alias

The alias call lets you merge different identities of a known user. It is an advanced method that lets you change the tracked user’s ID explicitly. You can use alias for managing the user’s identity in some of the downstream destinations.

warning

RudderStack supports sending alias events only to some downstream destinations.

See the destination-specific documentation for more information.

A sample alias call made using the Ruby SDK is shown below:

analytics.alias(
  previous_id: '1hKOmRA4GRlm',
  user_id: '12345'
)

The alias method parameters are as mentioned below:

FieldData typeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for the user in your database.
anonymous_id
Required, if user_id is absent.
StringUse this field to set an identifier when there is no unique user identifier available.
previous_id
Required
StringThe previous unique identifier of the user.
traitsObjectOptional dictionary of the user’s traits like name, email, etc.
integrationsObjectOptional dictionary containing the destinations to be either enabled or disabled.
contextObjectOptional dictionary of contextual information for the event. It is not directly related to the API call.
timestampTimestampThe event’s timestamp.

Note: 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 RudderStack.

Test mode

Use the SDK’s test mode to capture events locally without sending them to RudderStack:

analytics = Rudder::Analytics.new(
  write_key: 'WRITE_KEY',
  data_plane_url: 'DATA_PLANE_URL',
  test: true
)

analytics.track(
  user_id: '1hKOmRA4GRlm',
  event: 'Test Event',
  properties: { test: true }
)

# Access ALL captured events
analytics.test_queue.all.each do |msg|
  puts msg.inspect
end

Stub mode

Use the SDK’s stub mode to prevent actual network requests to RudderStack during testing:

analytics = Rudder::Analytics.new(
  write_key: 'WRITE_KEY',
  data_plane_url: 'DATA_PLANE_URL',
  stub: true
)

analytics.flush

## Gzip requests


info
The Gzip feature is enabled by default in the Ruby SDK.
The Ruby SDK automatically gzips requests. However, you can disable this feature by setting the `Gzip` parameter to `false` while initializing the SDK: ```ruby analytics = Rudder::Analytics.new( write_key: 'WRITE_KEY', # required data_plane_url: 'DATA_PLANE_URL', gzip: false # Set to true to enable Gzip compression )
warning
Gzip requires rudder-server v1.4 or higher. Otherwise, your events might fail.

Queue management

The Ruby SDK uses an in-memory queue to buffer events before sending. If the queue becomes full, events are dropped to prevent memory issues.

analytics = Rudder::Analytics.new(
  write_key: 'WRITE_KEY',
  data_plane_url: 'DATA_PLANE_URL',
  max_queue_size: 10000  # Increase for high-volume applications
)

Monitor queue size using:

analytics.queued_messages  # Returns number of queued messages

Flush events

Use flush to synchronously send all queued events to RudderStack.

info
The flush method is a blocking call that waits until the internal queue is drained.

You can use the flush method in the following scenarios:

  • In short‑lived scripts that exit immediately after sending events
  • Before shutting down a worker/process, or during graceful shutdown
  • Before deployments where the process is terminated

An example of using the flush method is shown below:

analytics.track(user_id: '1hKOmRA4GRlm', event: 'Job Finished')
analytics.flush  # Blocks until all queued events are sent

An example of using the flush method during a graceful shutdown is shown below:

at_exit do
  analytics.flush
end
info
Combine with retries and on_error handlers to observe delivery issues.

Flushing behavior

The Ruby SDK does not flush on fixed time intervals. Events are flushed automatically when either the batch reaches the configured batch_size, or the overall request size reaches 500 KB, whichever is earlier.

Note that:

  • The number of events per flush is configurable by the batch_size parameter (Default value: 100)
  • The flush API call is synchronous and waits until the queue is completely emptied.
info

High volume guidance

If your workloads are sending a large number of events at a time:

  • Increase the batch_size value so the SDK can send more events per request.
  • Increase the max_queue_size value substantially to provide headroom while the worker drains the queue. For very large bursts, for example, 100k+, size the queue at least 100× the burst to allow producers to continue enqueueing while consumers flush.
  • Always call the flush API call during graceful shutdown to ensure the queue is drained.

Customize retry behavior

By default, the Ruby SDK retries failed requests with an exponential backoff policy — this helps during temporary network issues or server problems.

For most use cases, the default behavior is suitable. However, you can customize it by passing a custom backoff policy during initialization, as shown:

# Define a custom backoff policy
custom_backoff = Rudder::Analytics::BackoffPolicy.new(
  min_timeout_ms: 200,        # Minimum wait time (milliseconds)
  max_timeout_ms: 20000,      # Maximum wait time (milliseconds)
  multiplier: 2.0,            # How much to multiply wait time per retry
  randomization_factor: 0.3   # Amount of randomness (0.0 to 1.0)
)

# Initialize the SDK with the custom backoff policy
analytics = Rudder::Analytics.new(
  write_key: 'WRITE_KEY',
  data_plane_url: 'DATA_PLANE_URL',
  backoff_policy: custom_backoff,
  retries: 5  # Number of retry attempts (default: 10)
)

The following are the parameters you can configure:

ParameterData type
Description
min_timeout_msIntegerMinimum wait time between retry attempts.

Default value: 100 ms
max_timeout_msIntegerMaximum wait time between retry attempts.

Default value: 10000 ms
multiplierFloatMultiplier applied to wait time for each retry attempt.

Default value: 1.5
randomization_factorFloatRandomness variation (0 to 1.0) added to prevent retry synchronization.

Default value: 0.5
info

When to use a custom backoff policy

Consider customizing the backoff policy only if:

  • You have strict latency requirements and want faster retries
  • You experience frequent rate limiting and need longer delays
  • You need to fine-tune retry behavior for your specific infrastructure

Troubleshooting

This section provides solutions to common issues encountered while using the Ruby SDK.

Events not sent

If events sent via the Ruby SDK are not appearing in your destinations:

analytics.flush
  • Check if the queue is full:
puts "Queued messages: #{analytics.queued_messages}"
  • Track any errors using an error handler:
analytics = Rudder::Analytics.new(
  write_key: 'WRITE_KEY',
  data_plane_url: 'DATA_PLANE_URL',
  on_error: proc { |status, error, exception, response|
    puts "Error occurred: #{status} - #{error}"
    puts "Exception: #{exception}" if exception
  }
)

Common errors

ErrorSolution
Missing required option :write_keyProvide a valid write key during initialization.
Missing required option :data_plane_urlProvide a valid data plane URL during initialization.
Must supply either user_id or anonymous_idProvide at least one identifier for each event.
Event must be givenProvide an event parameter to the track method.

Performance issues

If you are encountering performance issues when using the Ruby SDK in high-volume applications:

  • Increase the queue size by setting the max_queue_size parameter to a higher value during initialization.
max_queue_size: 20000
  • Adjust the batch size by setting the batch_size parameter to a higher value during initialization.
batch_size: 200

Examples

This section provides examples of how to use the Ruby SDK for some common use cases.

FAQ

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

The Ruby SDK drops any events greater than 32KB.

Does the Ruby SDK support event ordering?

The Ruby SDK does not support event ordering by default.

See more



Questions? Contact us by Email or on Slack