How to load data from Mandrill to Redshift (tutorial)

How to load data from SendGrid to Redshift

There’s a continually growing usage of services like Mandrill. Mandrill  is a transactional email API for Mailchimp Users and it is ideal for sending data-driven emails, including targeted and personalized one-to-one messages to your customers. But that traffic creates more data. How can you analyse the data you generate with Mandrill as part of your transactional email campaigns, on Amazon Redshift? This guide is going to provide you with a clear picture about how to load data from Mandrill to Redshift

Alternatively, in order to load your data from Mandrill to Redshift you can check Blendo that can handle this kind of problems automatically for you.

ETL your Mandrill data into your Data warehouse

We will use Mandrill’s API to access and extract e-mail related data and load it into Redshift for further analysis. You will need to write the code to get the data and make sure that this process will run every time new data are generated.

What is Mandrill?

Mandrill is a transactional email API for Mailchimp Users. Although in the past, Mandrill was perceived as a different product than Mailchimp, right now it is offered as a Mailchimp plugin. Mandrill is reliable, powerful and ideal for sending data-driven emails, including targeted and personalised one-to-one messages to your customers. You might wonder what are the differences between Mandrill and Mailchimp, as both of them handle the delivery of emails to your customers. Some key differences between the two are the following:

  • Mandrill is designed for developers. If you are not comfortable with writing code then it would be better if you find someone before you start using it. On the other hand, Mailchimp is designed mainly for marketeers so no technical skills are required to use it.
  • Mandrill focuses more on transactional e-mails, which are different than the promotional/campaign based emails that marketeers send using Mailchimp. Transactional e-mails are more tailor made for cases like one to one messages to your customers, like resetting passwords, welcoming them etc.
  • Mailchimp offers richer reporting, but with Mandrill it is easier to have access to all the raw events related to your e-mails as they happen, so you can run your own analytics if you wish. In general, raw data from Mandrill are much more accessible than in Mailchimp.
  • If you wish to run complicated campaigns with Mandrill you will have to implement the logic behind running them, with Mailchimp you can do that using the drag-n-drop environment that it offers.
How to load data from Mandrill to Redshift

How to load data from Mandrill to Redshift

In general, you can perceive the two services as complementary, Mailchimp allows your marketing department to easily and fast execute their marketing strategies, while with Mandrill you have access to a very flexible and rich environment where you can build complex products on top of e-mail services, but it requires the involvement of your R&D team.

Mandrill, as an email API, exposes all its functionality through it. So apart from being possible to execute a number of operations like sending emails based on specific events, we can also use this API to pull out data or setup our infrastructure in such a way that Mandrill will send to us data over time they are generated. In this article, we will see in detail the different ways of pulling data from Mandrill that can be useful for running our analytics.

What is Amazon Redshift?

Amazon Redshift is one of the most popular data warehousing solutions which is part of the Amazon Web Services (AWS) ecosystem. It is a petabyte scale, fully managed data warehouse as a service solution that runs on the cloud. It is SQL based and you can communicate with it as you would do with PostgreSQL, actually you can use the same driver although it would be better to use the drivers recommended by Amazon.

How to load data from Mandrill to Redshift

How to load data from Mandrill to Redshift

You can connect either through JDBC or ODBC connections.

How to Extract my data from Mandrill?

There are two main methods to get our data from Mandrill, the first one is to pull data out from it and the second one is to ask Mandrill to push data to us whenever something of importance happen. We will see the difference between these two solutions and how we can access data from both.

In order to pull data from Mandrill, we need to access its HTTP API. As a Web API following the RESTful architecture principles, it can be accessed through HTTP. As a RESTful API, interacting with it can be achieved by using tools like CURL or Postman or by using http clients for your favourite language or framework. A few suggestions:

Mandrill maintains a number of officially supported clients or SDKs that you can use with your favourite language to access it without having to mess with the raw underlying HTTP calls. These are the following:

How to load data from Mandrill to Redshift

 

There are also a number of unofficial clients that you can use if you prefer. The complete list can be found here.

In this post, we will consider the more generic case of accessing the HTTP endpoints directly for our examples, but of course, you are free to use the client of your choice for your project.

Mandrill API Authentication

In order to use the Mandrill API, you first have to generate an API key through your MandrillApp account. When you have created the key you can use it to access the API. You can actually have multiple keys per account something that adds versatility to the platform. In most cases with the Mandrill API, you make a POST call to access an endpoint with a JSON body containing the access key.

Mandrill rate limiting

API rate limiting with Mandrill is a bit of a more complicated matter than in most cases of APIs out there. The reason is that Mandrill is mainly an SMTP as a service platform, in most cases when we make a call to its API we do it in order to send an e-mail to someone, so rate limiting in the typical sense that we find it in web APIs does not apply in Mandrill. What is actually happening, is that every Mandrill account has a reputation and an hourly quota, the main reason that rate limiting is a bit more complicated in Mandrill is because they need to take special care of pointing out and handling potential spammers. So the hourly quota is affected by your reputation, if for example you have poor reputation then Mandrill will reduce the number of e-mails and consequently the API calls that you can do on a per hour basis, on the contrary if you have an excellent reputation you will be able to make more calls. Free accounts can send up to 25 emails per hour. If you want to find your hourly quota and reputation you will have to check your Dashboard in MandrillApp.

Endpoints and available resources

Mandrill exposes the following endpoints:

  • Users: Information about your account, for example here you can validate that your API key is valid.
  • This endpoint is used to send messages through the Mandrill API.
  • Information and operation about user defined tags.
  • Rejects. Manage your email rejection list.
  • Whitelists. Manage your rejection whitelists.
  • Senders. Manage senders associated with your Mandrill account.
  • Get information about the URLs that are included in your e-mails.
  • Manage e-mail templates.
  • Webhooks. Manage webhooks for your account.
  • Subaccounts. Manage subaccounts.
  • Information about domains that have been configured for inbound delivery.
  • Run export jobs to retrieve data from your Mandrill account.
  • IPs. Information and operations about your dedicated IPs.
  • Information and operations about your custom metadata fields indexed for the account.

The above endpoints define the complete set of operations that we perform with Mandrill, in our case we care mainly about what data we can export so we will work with the export endpoint. Export jobs can be executing for the following data:

  • Export your rejection blacklist.
  • Export your rejection whitelist.
  • Export your activity history.

We assume that you would like to export your activity data. In order to do that you need to perform a POST request to the following endpoint:

/exports/activity.json

Keep in mind that the base url might change depending on the warehouse where your application is hosted. For this reason we will mention only the endpoints and you will have to prepend the base url for your case.

The body that we should post to the above end-point should look like this.

{
    "key": "example key",
    "notify_email": "notify_email@example.com",
    "date_from": "2013-01-01 12:53:01",
    "date_to": "2013-01-06 13:42:18",
    "tags": [
        "example-tag"
    ],
    "senders": [
        "test@example.com"
    ],
    "states": [
        "sent"
    ],
    "api_keys": [
        "ONzNrsmbtNXoIKyfPmjnig"
    ]
}

We need to provide our api key, and we can also define a date range from which the API will collect data for. If we want we can filter even more the data we will get back by requesting specific tags or senders and states.

The results will include fields about:

  • Date
  • Email address
  • Sender
  • Subject
  • Status
  • Tags
  • Opens
  • Clicks
  • bounce details

When the export job finishes, the data will be available through a URL in a gziped format. Keep in mind that you will have to poll the Exports endpoint to figure out when the job is finished and get the exact url from which you will get the data. To do that you need to perform a POST request to the following end-point:

/exports/info.json

The body of the POST request should be a JSON document containing your api-key. You will get back a result like the following:

{
    "id": "2013-01-01 12:20:28.13842",
    "created_at": "2013-01-01 12:30:28",
    "type": "activity",
    "finished_at": "2013-01-01 12:35:52",
    "state": "working",
    "result_url": "http://exports.mandrillapp.com/example/export.zip"
}

As you can see from the response, we get a URL from which we can fetch the data and information about the completion or not of the job, if the state of the job is “complete” then we can safely download the data and further process it.

Another way of getting data from the Mandrill API is to ask it to push events to our system every time something of importance to happen. To do that, we need to setup web hooks on our system and provide the URLs to Mandrill. The platform will POST data in JSON format to these URLs every time an event is triggered. The good thing about this mechanism is that we can have the data as soon as possible in our system for analysis.

 Every Mandrill webhook uses the same general data format, regardless of the event type. The webhook request is a standard POST request with a single parameter (currently) – mandrill_events.

There are three types of webhooks that Mandrill currently POSTs: Message webhooks (such as when a message is sent, opened, clicked, rejected, deferred, or bounced), Sync webhooks, and Inbound webhooks.

The mandrill_events parameter contains a JSON-encoded array of webhook events, up to a maximum of 1000 events. Each element in the array is a single event, such as an open, click, or blacklist sync event. For examples of each type of event and a description of the keys, select the type of events you’ll be processing:

Message events (send, deferral, hard-bounce, soft-bounce, open, click, spam, unsub, reject)

Sync events (whitelist of blacklist sync)

Inbound messages

For more information about Webhooks, you can check here.

How can I prepare my Mandrill Data for Amazon Redshift?

Amazon Redshift is built around industry-standard SQL with added functionality to manage very large datasets and high performance analysis. So, in order to load your data into it you will have to follow its data model which is a typical relational database model. The data you extract from your data source should be mapped into tables and columns. Where you can consider the table as a map to the resource you want to store and columns the attributes of that resource. Also, each attribute should adhere to the datatypes that are supported by Redshift, currently the datatypes that are supported are the following:

  • SMALLINT
  • INTEGER
  • BIGINT
  • DECIMAL
  • REAL
  • DOUBLE PRECISION
  • BOOLEAN
  • CHAR
  • VARCHAR
  • DATE
  • TIMESTAMP

As your data are probably coming in a representation like JSON that supports a much smaller range of data types you have to be really careful about what data you feed into Redshift and make sure that you have mapped your types into one of the datatypes that is supported by Redshift. Designing a Schema for Redshift and mapping the data from your data source to it is a process that you should take seriously as it can both affect the performance of your cluster and the questions that you can answer. It’s always a good idea to have in your mind the best practices that Amazon has published regarding the design of a Redshift database. When you have concluded on the design of your database you need to load your data on one of the datasources that are supported as input by Redshift, these are the following:

 

How can I Load my data from Mandrill to Redshift?

The first step to load your data from Mandrill to Redshift, is to put them in a source that Redshift can pull it from. As it was mentioned earlier there are three main data sources supported, Amazon S3, Amazon DynamoDB and Amazon Kinesis Firehose, with Firehose being the most recent addition as a way to insert data into Redshift.

To upload your data to Amazon S3 you will have to use the AWS REST API, as we see again APIs play an important role in both the extraction but also the loading of data into our data warehouse. The first task that you have to perform is to create a bucket, you do that by executing an HTTP PUT on the Amazon AWS REST API endpoints for S3. You can do this by using a tool like CURL or Postman. Or use the libraries provided by Amazon for your favorite language. You can find more information by reading the API reference for the Bucket operations on Amazon AWS documentation.

After you have created your bucket you can start sending your data to Amazon S3, using again the same AWS REST API but by using the endpoints for Object operations. As in the Bucket case you can either access the HTTP endpoints directly or use the library of your preference.

DynamoDB imports data again from S3, it adds another step between S3 and Amazon Redshift so if you don’t need it for other reasons you can avoid it.

Amazon Kinesis Firehose is the latest addition as a way to insert data into Redshift and offers a real time streaming approach into data importing. The necessary steps for adding data to Redshift through Kinesis Firehose are the following:

  1. create a delivery stream
  2. add data to the stream

whenever you add new data to the stream, Kinesis takes care of adding these data to S3 or Redshift, again going through S3 in this case is redundant if your goal is to move your data to Redshift. The execution of the previous two steps can be performed either through the REST API or through your favourite library just as in the previous two cases. The difference here is that for pushing your data into the stream you’ll be using a Kinesis Agent.

Amazon Redshift supports two methods for loading data into it. The first one is by invoking an INSERT command. You can connect to your Amazon Redshift instance with your client, using either a JDBC or ODBC connection and then you perform an INSERT command for your data.

insert into category_stage values
(12, 'Concerts', 'Comedy', 'All stand-up comedy performances');

The way you invoke the INSERT command is the same as you would do with any other SQL database, for more information you can check the INSERT examples page on the Amazon Redshift documentation.

Redshift is not designed for INSERT like operations, on the contrary, the most efficient way of loading data into it is by doing bulk uploads using a COPY command. You can perform a COPY command for data that lives as flat files on S3 or from an Amazon DynamoDB table. When you perform COPY commands, Redshift is able to read multiple files in simultaneously and it automatically distributes the workload to the cluster nodes and performs the load in parallel. As a command COPY is quite flexible and allows for many different ways of using it, depending on your  use case. Performing a COPY on amazon S3 is as simple as the following command:

copy listing
from 's3://mybucket/data/listing/'
credentials 'aws_access_key_id=;aws_secret_access_key=';

For more examples on how to invoke a COPY command you can check the COPY examples page on Amazon Redshift documentation. As in the INSERT case, the way to perform the COPY command is by connecting to your Amazon Redshift instance using a JDBC or ODBC connection and then invoke the commands you want using the SQL Reference from Amazon Redshift documentation.

What is the best way to load data from Mandrill to Amazon Redshift and what are the possible alternatives?

So far we just scraped the surface of what can be done with Amazon Redshift and how to load data into it. The way to proceed relies heavily on the data you want to load, from which service they are coming from and the requirements of your use case. Things can get even more complicated if you want to integrate data coming from different sources.

A possible alternative, instead of writing, hosting and maintaining a flexible data infrastructure, is to use an ETL as a service product like Blendo that can handle this kind of problems automatically for you.

Blendo integrates with multiple sources or services like databases, CRM, email campaigns, analytics and more.  Quickly and safely move all your data from Mandrill into Amazon Redshift and start generating insights from your data.


Want to save hours on your data management tasks? Blendo can help!

Try Blendo for FREE NOW!

How to load data from Mandrill to Redshift