Use RudderStack’s Ruby SDK to send server-side events from your Ruby applications to various destinations asynchronously.
14 minute read
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.
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.
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
Add the following line to your application’s Gem file:
gem'rudder-sdk-ruby'
Run bundle install to install the gem.
Initialize the SDK
To initialize the SDK, create a client instance as shown below:
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.
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_idevery 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:
Use this field to set an identifier when there is no unique user identifier available.
traits
Object
Optional dictionary of user traits, like name, email, etc.
context
Object
Optional dictionary of contextual information for the event. It is not directly related to the API call.
integrations
Object
Optional dictionary containing the destinations to be either enabled or disabled.
timestamp
Timestamp
The 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:
The track method parameters are as described below:
Field
Data type
Description
user_id Required, if anonymous_id is absent.
String
Unique identifier for the user in your database.
anonymous_id Required, if user_id is absent.
String
Use this field to set an identifier when there is no unique user identifier available.
event Required
String
Name of the event.
properties
Object
Optional dictionary of the properties associated with the event.
context
Object
Optional dictionary of contextual information for the event. It is not directly related to the API call.
integrations
Object
Optional dictionary containing the destinations to be either enabled or disabled.
timestamp
Timestamp
The 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:
The page method parameters are as described below:
Field
Data type
Description
user_id Required, if anonymous_id is absent.
String
Unique identifier for the user in your database.
anonymous_id Required, if user_id is absent.
String
Use this field to set an identifier when there is no unique user identifier available.
name
String
Name of the viewed page.
properties
Object
Optional dictionary of the properties associated with the viewed page, like url, referrer, etc.
context
Object
Optional dictionary of contextual information for the event. It is not directly related to the API call.
integrations
Object
Optional dictionary containing the destinations to be either enabled or disabled.
timestamp
Timestamp
The 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.
The screen method parameters are as described below:
Field
Data type
Description
user_id Required, if anonymous_id is absent.
String
Unique identifier for the user in your database.
anonymous_id Required, if user_id is absent.
String
Use this field to set an identifier when there is no unique user identifier available.
name Required
String
Name of the viewed screen.
category
String
The screen’s category.
properties
Object
Optional dictionary of the properties associated with the viewed screen.
integrations
Object
Optional dictionary containing the destinations to be either enabled or disabled.
context
Object
Optional dictionary of contextual information for the event. It is not directly related to the API call.
timestamp
Timestamp
The 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:
Use this field to set an identifier when there is no unique user identifier available.
group_id Required
String
Unique identifier of the group in your database.
traits
Object
Optional dictionary of the group’s traits like name, email, etc.
integrations
Object
Optional dictionary containing the destinations to be either enabled or disabled.
context
Object
Optional dictionary of contextual information for the event. It is not directly related to the API call.
timestamp
Timestamp
The 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.
RudderStack supports sending alias events only to some downstream destinations.
The alias method parameters are as mentioned below:
Field
Data type
Description
user_id Required, if anonymous_id is absent.
String
Unique identifier for the user in your database.
anonymous_id Required, if user_id is absent.
String
Use this field to set an identifier when there is no unique user identifier available.
previous_id Required
String
The previous unique identifier of the user.
traits
Object
Optional dictionary of the user’s traits like name, email, etc.
integrations
Object
Optional dictionary containing the destinations to be either enabled or disabled.
context
Object
Optional dictionary of contextual information for the event. It is not directly related to the API call.
timestamp
Timestamp
The 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 eventsanalytics.test_queue.all.eachdo|msg|putsmsg.inspectend
Stub mode
Use the SDK’s stub mode to prevent actual network requests to RudderStack during testing:
The Gzip feature is enabled by default in the Ruby SDK.
TheRubySDKautomaticallygzipsrequests.However,youcandisablethisfeaturebysettingthe`Gzip`parameterto`false`whileinitializingtheSDK:```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
)
Gzip requires rudder-serverv1.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.
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_exitdoanalytics.flushend
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.
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 policycustom_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 retryrandomization_factor:0.3# Amount of randomness (0.0 to 1.0))# Initialize the SDK with the custom backoff policyanalytics=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:
Parameter
Data type
Description
min_timeout_ms
Integer
Minimum wait time between retry attempts.
Default value: 100 ms
max_timeout_ms
Integer
Maximum wait time between retry attempts.
Default value: 10000 ms
multiplier
Float
Multiplier applied to wait time for each retry attempt.
Default value: 1.5
randomization_factor
Float
Randomness variation (0 to 1.0) added to prevent retry synchronization.
Default value: 0.5
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:
Provide a valid data plane URL during initialization.
Must supply either user_id or anonymous_id
Provide at least one identifier for each event.
Event must be given
Provide 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.
The following example tracks the user’s shopping behavior from browsing to purchase:
# Product Viewedanalytics.track(user_id:'1hKOmRA4GRlm',event:'Product Viewed',properties:{product_id:'SKU-123',sku:'SKU-123',name:'Ruby SDK Guide',price:29.99,currency:'USD',category:'Books'})# Product Added to Cartanalytics.track(user_id:'1hKOmRA4GRlm',event:'Product Added',properties:{product_id:'SKU-123',cart_id:'CART-789'})# Order Completedanalytics.track(user_id:'1hKOmRA4GRlm',event:'Order Completed',properties:{order_id:'ORD-456',total:35.98,revenue:35.98,currency:'USD',products:[{product_id:'SKU-123',quantity:1,price:29.99}]})analytics.flush
The following example tracks the complete user journey:
# New user signupanalytics.identify(user_id:'1hKOmRA4GRlm',traits:{email:'newuser@example.com',name:'John Doe',created_at:Time.now,signup_source:'website'})# Track activation eventanalytics.track(user_id:'1hKOmRA4GRlm',event:'User Activated',properties:{plan:'free',feature:'project_creation'})# Upgrade to paid plananalytics.track(user_id:'1hKOmRA4GRlm',event:'Subscription Upgraded',properties:{previous_plan:'free',new_plan:'pro',revenue:49.99,currency:'USD'})analytics.flush
The following example tracks organization-level events and user-to-organization relationships:
This site uses cookies to improve your experience while you navigate through the website. Out of
these
cookies, the cookies that are categorized as necessary are stored on your browser as they are as
essential
for the working of basic functionalities of the website. We also use third-party cookies that
help
us
analyze and understand how you use this website. These cookies will be stored in your browser
only
with
your
consent. You also have the option to opt-out of these cookies. But opting out of some of these
cookies
may
have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This
category only includes cookies that ensures basic functionalities and security
features of the website. These cookies do not store any personal information.
This site uses cookies to improve your experience. If you want to
learn more about cookies and why we use them, visit our cookie
policy. We'll assume you're ok with this, but you can opt-out if you wish Cookie Settings.