<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Roma Glushko 🦁 on Medium]]></title>
        <description><![CDATA[Stories by Roma Glushko 🦁 on Medium]]></description>
        <link>https://medium.com/@roma-glushko?source=rss-2607aea71af1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SUOEdVNME9GoCGXo3o1z2A.jpeg</url>
            <title>Stories by Roma Glushko 🦁 on Medium</title>
            <link>https://medium.com/@roma-glushko?source=rss-2607aea71af1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:32:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roma-glushko/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Papercups: How to design a customer Service Platform?]]></title>
            <link>https://roma-glushko.medium.com/how-to-design-a-customer-service-platform-papercups-65fa71eb2e25?source=rss-2607aea71af1------2</link>
            <guid isPermaLink="false">https://medium.com/p/65fa71eb2e25</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[customer-engagement]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[Roma Glushko ]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 19:36:41 GMT</pubDate>
            <atom:updated>2024-10-24T19:36:41.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2pgnqw9wZOHw6oNY.jpg" /><figcaption>Photo by <a href="https://unsplash.com/@yeehawprint"><strong>Archer Fu</strong></a></figcaption></figure><p>We are living in an interesting time, where large language models are reshaping the way we interact with the world. One of the areas where this impact is most noticeable is in communication with real people, such as in customer support.</p><p>It used to be necessary to have a team handle all of a company’s interactions with customers — answering phones, emails, and live chats. This is changing as AI has advanced enough to provide seamless, high-quality conversations with humans.</p><p>That said, we still need to build the supporting infrastructure to integrate LLMs.</p><p>In this episode, we’ll explore how to build a communication platform similar to <a href="https://www.zendesk.com/"><strong>Zendesk</strong></a> or <a href="https://www.intercom.com/"><strong>Intercom</strong></a>. We’ll use the Papercups architecture as our example.</p><p><a href="https://github.com/papercups-io/papercups"><strong>Papercups</strong></a> is a self-hosted, open-source customer service platform. It integrates with various communication channels like <a href="https://www.romaglushko.com/blog/papercups/#email-forwarding"><strong>email</strong></a>, <a href="https://www.romaglushko.com/blog/papercups/#sms"><strong>SMS</strong></a>, <a href="https://slack.com/"><strong>Slack</strong></a>, <a href="https://mattermost.com/"><strong>Mattermost</strong></a>, and <a href="https://www.romaglushko.com/blog/papercups/#live-chat-widget"><strong>a live chat widget</strong></a> on your website or mobile app.</p><blockquote>The original article was posted on <a href="https://www.romaglushko.com/blog/papercups/">my website</a>. Go and check it out 👀</blockquote><h3>Architecture</h3><p>We’ll kick off our review with the high-level architecture of Paparcups.</p><figure><img alt="The Papercups High-Level Architecture | Papercups | Customer Service Platform" src="https://cdn-images-1.medium.com/max/1024/0*J0727i9x-UXeetwP.png" /><figcaption>The Papercups High-Level Architecture</figcaption></figure><p>First off, the Papercups API is built with <a href="https://elixir-lang.org/"><strong>Elixir</strong></a> and <a href="https://www.phoenixframework.org/"><strong>Phoenix Framework</strong></a>. Elixir is well-regarded in the communications space, with companies like Discord, PagerDuty, Podium, and others. It’s a functional and very readable language that compiles back to <a href="https://www.erlang.org/blog/a-brief-beam-primer/"><strong>the Erlang’s BEAM virtual machine</strong></a>.</p><p>The API is a single monolithic deployment and uses <a href="https://www.postgresql.org/"><strong>PostgreSQL</strong></a> for data storage, along with an object storage (<a href="https://aws.amazon.com/s3/"><strong>AWS S3</strong></a> for file attachments.</p><p>Asynchronous background tasks are handled using <a href="https://getoban.pro/"><strong>Oban</strong></a>.</p><p>From a UI perspective, we have the Dashboard UI and a special live chat widget that’s designed to be embedded into other websites.</p><p>The live chat is powered by <a href="https://hexdocs.pm/phoenix/channels.html"><strong>Phoenix Channels</strong></a> &amp; <a href="https://hexdocs.pm/phoenix/presence.html"><strong>Presence</strong></a>.</p><p>The architecture seems like a solid choice for a startup project.</p><h3>Accounts &amp; Users</h3><p>To get a better grasp of what Papercups offers, let’s dive into its data model. We’ll start with accounts, users and customers models, as they’re key to understanding how everything else connects.</p><blockquote>When we review the data model, we’ll skip over some common fields like id, inserted_at and updated_at to keep things concise—unless they’re important for understanding a specific table.</blockquote><p>We’ll also leave out foreign keys for the same reason, and instead, use arrows to represent them.</p><figure><img alt="The Account Data Model | Papercups | Customer Service Platform" src="https://cdn-images-1.medium.com/max/1024/0*Nr1Rh7XboTX-U8n9.png" /><figcaption>The Account Data Model</figcaption></figure><h3>Accounts</h3><p>The Account is the core entity in the system. It holds <a href="https://www.romaglushko.com/blog/papercups/#billing"><strong>billing information</strong></a> and key details about your company, such as company_name, company_logo_url or working_hours. Additionally, the Account table includes general limits and settings.</p><h3>Users</h3><p>The Account has Users who are employees of the company that serve their Customers. The User table includes standard information like email, role, pass_hash, and so on. The information shown when a User is chatting with a Customer is kept in a separate table UserSettings. Unlike the Accounts table, the Users table doesn’t have any settings. These are stored in the UserSettings table instead.</p><p>There are two roles for Users: member and admin. Admins have more permissions, including the ability to set up integrations.</p><p>Users can be invited by generating an invitation link, which is tied to a specific Account. The link expires either after three days or as soon as a new user is created using it (by setting the expiration time to now).</p><figure><img alt="The User Invitation Form" src="https://cdn-images-1.medium.com/proxy/0*kYgO_n2s7fqwcj4a.png" /><figcaption>The User Invitation Form</figcaption></figure><blockquote><strong><em>UUID as Primary Keys</em></strong></blockquote><blockquote>Even though Papercups uses PostgreSQL, they’ve opted out of the default incremental integer primary keys. Instead, they stick with UUIDs for all their tables.</blockquote><blockquote>Using UUIDs is a smart move since it keeps your public-facing IDs in a format that’s hard to guess.</blockquote><p>The main admin who creates a new Account is registered via a separate form.</p><p>You can disable this registration path by setting an environment variable called PAPERCUPS_REGISTRATION_DISABLED. This is handy for on-premises setups where typically only one company uses the Papercups installation.</p><h3>Customers</h3><p>Customers are the people served by Account and its Users. Users have conversations with Customers.</p><p>The platform tries to create a Customer profile for any new interaction with the system and match the Customer with all previous interactions to provide a seamless experience.</p><p>Over time, Papercups may collect a lot of information about Customers and that may make it feel like a CRM system.</p><p>Papercups supports linking its Customer base with Hubspot or Intercom data, but we are not reviewing that one as it’s implemented as a rather simplistic one-way manual linking.</p><h3>Billing</h3><p>Papercups uses a straightforward fixed-price subscription model with three plans billed monthly. These plans differ in terms of user seat limit, message volume, data retention time and some features.</p><figure><img alt="The Price Structure" src="https://cdn-images-1.medium.com/max/1024/0*2s5p2cHsrETT4P4f.png" /><figcaption>The Price Structure</figcaption></figure><p>The Account can be one of these plans:</p><ul><li>Starter: A free plan that supports up to two users.</li><li>Lite: A paid plan that supports up to four users.</li><li>Team: A paid plan with no user limit.</li></ul><p>In addition to tracking users, they also monitor the number of messages that pass through the system. However, it looks like this information isn’t used for pricing.</p><p>They offer a different set of plans for EU customers, marked with an eu- prefix. These plans likely include VAT in the pricing and offer a different set of payment options.</p><h3>Subscriptions</h3><p>To actually do the billing, Papercups uses <a href="https://docs.stripe.com/billing/subscriptions/overview"><strong>Stripe’s Subscriptions</strong></a>.</p><figure><img alt="The Stripe Payment Objects" src="https://cdn-images-1.medium.com/max/1024/0*puf8ngFFT0ETr_-4.png" /><figcaption>The Stripe Payment Objects</figcaption></figure><p>In Stripe there are a few objects that pay together to create a recurring subscription:</p><ul><li>Product is essentially our subscription plan e.g. starter, lite, team.</li><li>Price contains information about price, currency and recurring interval. One product may have many Prices describing different billing options like paying once a month or once a year.</li><li>Stripe has its own Customer representation holding the information about the person or a company that receives our invoices.</li><li>Customers have their PaymentMethods which is the way to pay for the subscription.</li><li>Finally, Subscriptions tie all these objects together and state the subscription agreement.</li></ul><p>The subscription is created in the following way:</p><ul><li>Papercups creates a new Stripe Customer if Account has not referenced it yet. It uses email and company_name data for that.</li><li>Then, it allows you to create a new credit card-based PaymentMethod by filling a form in the Papercups Dashboard UI. The PaymentMethod gets attached to the Stripe Customer and referenced on the Account model.</li><li>After this, the user picks one of the plans and subscribes to it. Under the hood, Papercups fetches the Stripe Products to match it with the plan, then fetches all Prices and does a Subscription creation with that information. All plans come with a 14-day free trial (a Stripe Subscription option).</li></ul><p>On subscription cancellation, Papercups just deletes the previously created subscription and rolls back the plan to starter.</p><h3>Conversations</h3><p>Another crucial part of the Papercups system is the Conversation data model.</p><figure><img alt="The Conversation Data Model" src="https://cdn-images-1.medium.com/max/1024/0*Yz3zYQcdfjGIINe1.png" /><figcaption>The Conversation Data Model</figcaption></figure><blockquote><strong><em>Account Data Denormalization</em></strong></blockquote><blockquote>Notice how all tables contain account_id consistently across the system? This denormalization is a handy practice that simplifies data processing and retention in the future. It gives you enough context to get the job done without the hassle of resolving and reading from multiple tables.</blockquote><blockquote>Plus, this approach could also make splitting the monolithic API into microservices a lot easier.</blockquote><p>Conversations are made up of Messages. A new Conversation starts with the first Message.</p><p>A Conversation can be marked as important or not, and it can be either closed or open. Papercups tracks when the first reply happens to analyze agents’ response times.</p><p>Additionally, the system keeps track of whether and when new Messages are seen by Users and Customers to show this information in <a href="https://www.romaglushko.com/blog/papercups/#the-message-seen-or-not"><strong>the chat window</strong></a>.</p><p>Optionally, Conversations can be tagged with ConversationTags to help with filtering and searching them.</p><h3>Message Attachments</h3><p>Papercups lets Customers and Users attach files to their messages during <a href="https://www.romaglushko.com/blog/papercups/#live-chat-widget"><strong>live chat</strong></a> or <a href="https://www.romaglushko.com/blog/papercups/#email-forwarding"><strong>email</strong></a> conversations.</p><p>Live chat files are uploaded directly from <a href="https://www.romaglushko.com/blog/papercups/#live-chat-widget"><strong>the chat widget</strong></a>.</p><p>Papercups has a separate upload API where the widget sends an attachment as multipart form data. The API uploads the file to the AWS S3 bucket and creates a new FileUpload record that stores file metadata like the S3 file URL, content type, filename, etc.</p><p>The backend returns back the file metadata along with file_id. Finally, the chat widget passes the file_id reference along with message data to create a new Message record. The system creates a MessageFile link that attaches the file to the message.</p><h3>Message Notifications</h3><p>When a new Message is created, Papercups does a bunch of notifications depending on where the message came from:</p><ul><li>first of all, we notify the Customer back through the same channel they used to start the conversation which is either <a href="https://www.romaglushko.com/blog/papercups/#email-forwarding"><strong>email</strong></a>, SMS, GMail, or <a href="https://www.romaglushko.com/blog/papercups/#live-chat-widget"><strong>live chat notification</strong></a>.</li><li>broadcast a websocket message to Account admin channel</li><li>send <a href="https://www.romaglushko.com/blog/papercups/#webhooks--functions"><strong>a webhook notification</strong></a> to all subscribers</li><li>send a push notification to Users via <a href="https://docs.expo.dev/push-notifications/overview/"><strong>Expo</strong></a></li><li>send messages to <a href="https://www.romaglushko.com/blog/papercups/#reply-channels"><strong>the configured reply channels</strong></a> in Slack or Mattermost</li></ul><p>When a new Conversation is created, there are also some notifications:</p><ul><li>broadcasting a websocket message to all Users and in the Account</li><li>broadcasting a websocket message to Customer in the <a href="https://www.romaglushko.com/blog/papercups/#the-live-chatting"><strong>Conversation Lobby Channel</strong></a></li><li>sending <a href="https://www.romaglushko.com/blog/papercups/#webhooks--functions"><strong>a webhook notification</strong></a> to all subscribers</li></ul><h3>Conversation Reminders</h3><p>It’s entirely possible that some Conversations may get forgotten or lost in the shuffle. To help with this, the Account admin can set up a conversation reminder after a configured number of hours without a reply.</p><p>The reminder adds a new private message to the conversation thread that is visible to Users only.</p><p>The reminder message is marked in a special way to distinguish it from regular messages. Its metadata contains is_reminder flag and reminder_count that is incremented every time a new reminder message is added. The admin can configure the max number of consequent reminders to give their support team before giving up.</p><p>Reminder messages are also broadcasted to Slack, Mattermost, admin users, and webhooks like regular messages.</p><h3>Sharing Conversations</h3><p>You can share Conversations with anyone, even if they are outside the system.</p><p>Papercups creates a JWT token that includes signed data for account_id and customer_id . The convesation_id is simply included as a query parameter in the URL. This token is valid for one day.</p><p>Here’s what the sharing link looks like:</p><pre>http://localhost:4000/share?cid=6b5d64ae-6c6a-46de-b672-550cc204ee94&amp;token=SFMyNTY.g2gDaAJtAAAAJDBk...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cs3YqQ6_K1G0bucV.png" /><figcaption>The Shared Conversation</figcaption></figure><p>The shared conversation is rendered as a read-only conversation thread.</p><h3>Notes &amp; Canned Responses</h3><p>Users can assign multiple Notes to their Customers, adding private information that’s only visible to human agents.</p><p>Another handy feature is canned responses. These are predefined reply snippets you can quickly insert into your current message, making typing a breeze.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/0*IqBt5EQmGeOcJWrJ.png" /><figcaption>The Saved Reply Suggestion</figcaption></figure><p>Saved replies have short identifiers, like /into, that are used to look them up. The UI loads all the canned responses where the reply textbox appears and then suggests the appropriate reply when someone types /.</p><h3>Archiving Conversations</h3><p>Over time, the number of Conversations can grow significantly. To keep the system performant and responsive, Papercups archives certain stale Conversations.</p><p>For paid Accounts, the system automatically archives all closed Conversations that are 2 weeks old. For free starter Accounts, it archives all non-important Conversations that were inactive for a month.</p><p>After archiving, conversations are not available in the Papercups Dashboard and are not included anywhere else in the platform.</p><blockquote><strong><em>Soft-Deletion</em></strong></blockquote><blockquote>Archiving records like this is more commonly known as soft deletion. With soft deletion, the removed data is just marked as deleted and still technically there, but not shown in the UI. The user still has a chance to change their mind and restore deleted records for some period of time like one month. After that, the data is deleted forever (a.k.a. hard deletion).</blockquote><blockquote>Besides being a useful technique to cope with incidental data loss, soft-deletion might be required for audit and legal purposes (for example, the HIPAA compliance requires data to be available for an extended period of time).</blockquote><h3>Inboxes</h3><p>Papercups makes it easy to start a conversation with a customer through various channels like email, SMS, Slack, live chat widgets, and Gmail. All messages from these sources are collected into one or a few Inboxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UpP0REcvzk5ay996.png" /><figcaption>The Inboxes</figcaption></figure><p>Inbox is an abstraction around the communication channels and a way to group your conversations by sources, so all conversations coming into one Inbox look like they were coming from one and the same channel.</p><p>To play this abstraction game til the end, Papercups replies back seamlessly via the channel the conversation was started initially, so Users have to deal with the chat UX no matter how the conversation has landed on the platform.</p><p>The InboxMembers is the way to subscribe Users to the corresponding notifications about new messages in the Inbox (doesn’t seem to be fully implemented in Papercups though).</p><h3>Email Forwarding</h3><p>Receiving emails is implemented via <a href="https://aws.amazon.com/ses/"><strong>AWS Simple Email Service (SES)</strong></a>.</p><p>First off, you would need to generate a unique forwarding email associated with your specific Inbox.</p><blockquote><strong><em>Random Forwarding Emails</em></strong></blockquote><blockquote>Papercups uses the following algorithm to generate random local part of forwarding email addresses:</blockquote><blockquote>:crypto.strong_rand_bytes(32)<br>|&gt; Base.encode32()<br>|&gt; binary_part(0, 32)<br>|&gt; String.downcase()</blockquote><blockquote>The email domain part is fixed and has to be whitelisted in AWS SES.</blockquote><p>The forwarding email is generated at a specific domain that is verified in AWS SES and linked to SES’s email servers via MX records.</p><p>Then, you likely need to point your customer-facing email (e.g. <a href="/service/mailto:support@acme.com"><strong>support@acme.com</strong></a>) to the forwarding one. This is a common functionality that domain registrars provide. Gmail supports this natively too via <a href="https://support.google.com/mail/answer/10957?hl=en"><strong>their account settings</strong></a>.</p><figure><img alt="The Email Forwarding Workflow" src="https://cdn-images-1.medium.com/max/1024/0*v2mz5Wo79D8X5isT.png" /><figcaption>The Email Forwarding Workflow</figcaption></figure><p>Once someone sends an email to the customer-facing email, it gets forwarded all the way to the AWS SES.</p><p>Upon receiving an email, SES dumps it as a file into the S3 bucket under the unique message_id which is then passed over in the webhook payload. This includes email attachment files, too.</p><p>Finally, SES sends a webhook call to Papercups API with message_id, from and to email addresses along with the Received header that contains additional information about email routing path.</p><h3>Email Format</h3><p>There is <a href="https://www.rfc-editor.org/rfc/rfc2822"><strong>RFC2822</strong></a> that defines the email file format that SES uses to share emails with their client applications.</p><p>It may be worth pausing for a second to look at raw email format.</p><p>The email format is awfully close to the HTTP request/response format. There is a header with a list of well-defined and custom fields (prefixed by X- just like in the HTTP convention) and a body that holds the actual email content.</p><p>Here is a list of common email header fields:</p><h4>Sender Fields</h4><ul><li>From - The email address of the sender. It can be a list of addresses then a separate Sender field has to be set to</li><li>Reply-To - an optional field that specifies the email addresses to which replies should be sent by default. Normally, From is used for that.</li></ul><h4>Receiver Fields</h4><ul><li>To - a list of email addresses that the email is sent to. There are primary recipients.</li><li>Cc - a list of email addresses that receive the email, and it’s not directed to them (a.k.a. carbon copies).</li><li>Bcc - a list of email addresses that receive the message but don’t have to be revealed to other participants (a.k.a. blind carbon copies).</li></ul><h4>Identification Fields</h4><ul><li>Message-ID is a unique identifier for the email generated by the email client</li><li>In-Reply-To contains a Message-ID of the email that this email is a reply to</li><li>References is a conversation history in the form of a list of previous Message-IDs up to this reply</li></ul><h4>Info Fields</h4><ul><li>Subject - the subject of the email thread</li><li>Received - a list of email servers that the email has passed through. It’s a good way to track the email routing path.</li></ul><p>Here is an example of a raw email:</p><pre>From: &quot;Dwight Shrut&quot; &lt;dwight.shrut@dundermifflin.com&gt;<br>To: michael.scott@dundermifflin.com<br>Subject: Another prank<br>Message-ID: &lt;CAEkJ+_b2Y4bu6gn-xp3aM+ujD8An9mNq9WzwvtrMWoDQBYZW4Q@mail.gmail.com&gt;<br>Received: from 52669349336 named unknown by gmailapi.google.com with HTTPREST; Fri, 2 Aug 2024 04:32:44 -0700<br>Received: from mail-sor-f65.google.com (mail-sor-f65.google.com. [209.85.220.65])<br>        by mx.google.com with SMTPS id 00721157ae682-68a10658756sor13094707b3.5.2024.08.02.04.32.45<br>        for &lt;michael.scott@dundermifflin.com&gt;<br>        (Google Transport Security);<br>        Fri, 02 Aug 2024 04:32:46 -0700 (PDT)Date: Fri, 2 Aug 2024 04:32:44 -0700<br>MIME-Version: 1.0<br>Content-Type: multipart/alternative; boundary=&quot;000000000000a7bf26061eb1af2b&quot;<br>--000000000000a7bf26061eb1af2b<br>Content-Type: text/plain; charset=&quot;UTF-8&quot;<br>Content-Transfer-Encoding: quoted-printable<br>Michael, Jim put put my stuff in jello again!<br>Can you please punish him?<br>--000000000000a7bf26061eb1af2b<br>Content-Type: text/html; charset=&quot;UTF-8&quot;<br>&lt;div dir=3D&quot;ltr&quot;&gt;Michael, Jim put put my stuff in jello again!&lt;br/&gt;<br>&lt;div&gt;Can you please punish him?&lt;/div&gt;<br>&lt;/div&gt;<br>--000000000000a7bf26061eb1af2b--</pre><h3>Conversation Matching</h3><p>At this point, Papercups has only a reference to the received email and a bunch of email addresses associated with it. Papercups doesn’t do the webhook processing immediately, but rather add a new task to the distributed queue.</p><p>The task worker pulls the email file from the S3 bucket first, creates a new conversation or a message based on the email, and <a href="https://www.romaglushko.com/blog/papercups/#message-attachments"><strong>attaches any email files to the message</strong></a> including preloading them to the attachment bucket for permanent storage.</p><p>Users are assumed to be replying via the system, so the only person who can email us is the Customer. Hence, the From email address is used to find or create a Customer.</p><p>When User replies to an existing email thread via the system, the reply email is formed in a specific way:</p><ul><li>The system puts a generic email e.g. {User.name} &lt;mailer@chat.papercups.io into the From header. The From email is still under the domain linked with AWS SES, so we will receive any replies to it.</li><li>Papercups makes use of the Reply-To header and sets it to reply+{conversationID}@chat.papercups.io which means that this is the default reply email in email clients (unless Customer changes the corresponding field).</li></ul><p>After that, Papercups just tries to find if there is any mention of the reply+ email address among all places and if so, we are dealing with a reply to an existing Conversation.</p><h3>Gmail Sync</h3><p>Besides the ability to <a href="https://www.romaglushko.com/blog/papercups/#email-forwarding"><strong>forward Gmail emails</strong></a>, Papercups can also sync your Gmail messages.</p><p>To attain that, Users need to authorization Papercups to work with their Gmail account. Google supports <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/which-oauth-2-0-flow-should-i-use"><strong>the OAuth2 Authorization Code workflow</strong></a> specifically for that.</p><p>The system requests <a href="https://developers.google.com/gmail/api/auth/scopes"><strong>the gmail.modify scope</strong></a> and the offline access mode to indicate that it’s going to be used with further Users involvements to power background syncs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FZfia6zYLs1E6Av9.png" /><figcaption>Gmail Sync Workflow</figcaption></figure><p>At the end of the authorization workflow e.g. the callback stage, Papercups does the access token request and persists the receives information like refresh_token, scope, client_type and of course it links the authorization to a specific Account, Inbox, and User.</p><blockquote><strong><em>The least privilege principle</em></strong></blockquote><blockquote>Papercups supports syncing messages with Gmail and Customer data with Google Spreadsheets. Each functionality acts via a separate authorization workflow that requests different authorization scopes strictly sufficient to perform its job.</blockquote><blockquote>The client_type field serves a way to differentiate between these two sets of credentials.</blockquote><blockquote>This reminds me of the least privilege principle that encourages to give other parties as few permissions as possible to perform a given task. Even though Papercups works with both Gmail and Google Spreadsheets, the specific Account may never need to sync their Customers with spreadsheets, for example, so no need to ask for that permission.</blockquote><p>Then Papercups triggers a specific background task to enable message syncing. That process fetches <a href="https://developers.google.com/gmail/api/reference/rest/v1/users.threads/list"><strong>the list of the most recent Gmail threads</strong></a> and identifies where we are in the Gmail history stream by extracting the history_id from the most recently updated thread.</p><p>The history_id points to a place in the Gmail history stream from where we should start pulling updates. This is a good way to incrementally synchronize data between systems without repulling the whole thread collection every time. That’s why Papercups saves the history_id until the next sync attempt as metadata on the GoogleAuthorization table.</p><p>Unlike the <a href="https://www.romaglushko.com/blog/papercups/#email-forwarding"><strong>email forwarding</strong></a> and <a href="https://www.romaglushko.com/blog/papercups/#sms"><strong>SMS</strong></a> workflows where the system was pinged by webhooks, Gmail sync is based on the pull model, so we need to periodically check out if there are any updates.</p><p>When pulling updates, Papercups fetches all history items of the messageAdded type. Messages that were labeled as spam, draft, promotions are filtered out. If the whole Gmail thread is filled with these messages, it’s skipped.</p><p>Then, the system processes the remaining <a href="https://developers.google.com/gmail/api/reference/rest/v1/users.messages#Message"><strong>Gmail messages</strong></a> thread by thread. Papercups maintains Gmail thread metadata in a separate GmailConversationThread table that is linked with the main Conversation entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*45doqWDB5dEWj0Uv.png" /><figcaption>Gmail Data Model</figcaption></figure><p>If the Gmail thread is already known to the system, Papercups just loads all existing Conversation messages, collects gmail_id from their metadata and adds only messages with new gmail_ids.</p><p>For the new GMail thread, Papercups creates a new Conversation and links a new GmailConversationThread to it. Papercups uses the first message in the thread to understand how the thread was created.</p><p>If the message contains the SENT label, then the from email address is the User email and the to email address is the Customer email. If no Users is found under the email address, Papercups uses the User that has enabled the Gmail sync.</p><p>Finally, Papercups adds new Conversation messages based on GMail messages. It copies a lot of metadata as is from the Gmail message like gmail_id, gmail_message_id, gmail_thread_id gmail_history_id, gmail_label_ids, and various email headers like FROM, TO, BCC, References, In-Reply-To, etc.</p><p>As a part of message creation, we also reupload the <a href="https://developers.google.com/gmail/api/reference/rest/v1/users.messages.attachments"><strong>GMail attachments</strong></a> to our object storage.</p><blockquote><strong><em>Keep External Data As Is</em></strong></blockquote><blockquote>Gmail is an external system that sends us some data that we base our logic on. It’s a good idea to keep the parts of the raw data that we care about, so we have an easy way to pinpoint problems related to some edge cases in that data by inspecting the original external data.</blockquote><h3>SMS</h3><p>The platform can use SMS as a conversation source as well. For that, it uses <a href="https://www.twilio.com/en-us"><strong>Twilio SMS Receiving Service</strong></a>.</p><p>Twilio gives you a phone number, Twilio Account SID and Auth Token that you set in Papercups. Along with that, you need to set a webhook URL in Twilio to point to the Papercups backend. Papercups validates the credentials by simply hitting the Twilio List Messages API endpoint.</p><p>Once a new SMS is received, Twilio sends a webhook request with Twilio Account SID, message body, from and to phone numbers.</p><p>Just like with emails, the from phone number serves as an identifier of the Customer. The Twilio Account SID and the to phone number are used to match the integration that contains references to the Account and Inbox.</p><p>In the context of SMS conversations, we still have absolutely <a href="https://www.romaglushko.com/blog/papercups/#conversation-matching"><strong>the same problem</strong></a> of identifying whether this specific message is a part of the existing conversation or a new one.</p><p>However, SMS communication has even less flexibility for conversation linking, Papercups has to basically guess based on the existing data like the Customer, conversation source, Inbox. So it pulls the last active conversations based on these criteria and assumes it to be the one associated with the given SMS.</p><h3>Live Chat Widget</h3><p>One of the most interesting conversation sources is the live chat embedded directly on a website (or a mobile application, but we will focus on the website case here).</p><h3>Widget Initialization</h3><p>The live chat widget is inited in two steps.</p><ul><li>Papercups introduces a new window field Papercups with the widget configuration. The configuration includes the connection information, look &amp; feel configs, and a few configurations that control the widget behavior (e.g. show agent availability, require email to start a conversation, open the chat window on widget load or not, etc.).</li><li>Then, we load the embedded widget script itself in a deferred asynchronous way (not to block anything important).</li></ul><pre>&lt;script&gt;<br>    window.Papercups = {<br>        config: {<br>            token: &quot;&lt;ACCOUNT_ID&gt;&quot;,<br>            inbox: &quot;&lt;INBOX_ID&gt;&quot;,<br>            title: &quot;Welcome to DunderMifflin&quot;,<br>            subtitle: &quot;Ask us anything in the chat window below&quot;,<br>            primaryColor: &quot;#7bdcb5&quot;,<br>            showAgentAvailability: true,<br>            requireEmailUpfront: true,<br>        },<br>    };<br>&lt;/script&gt;<br> <br>&lt;script<br>    type=&quot;text/javascript&quot;<br>    async<br>    defer<br>    src=&quot;http://app.papercups.io/widget.js&quot;<br>&gt;&lt;/script&gt;</pre><p>The widget script uses the window.Papercups configuration to render the chat toggle button and the chat window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*20UVtOKn8tecVwBs.png" /><figcaption>The Live Chat Window</figcaption></figure><p>Additionally, the widget script exposes open(), close() and toggle() functions to show or hide the chat window from the external code. Papercups leverages <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent"><strong>custom events</strong></a> (e.g. papercups:open) under the hood in the methods to let external scripts to trigger the corresponding actions.</p><p>Architecturally, the chat widget has three parts:</p><ul><li>A shared library called Papercups/Browser. The library contains a set of methods to interact with Papercups REST and websocket API, and a singleton “brain” object to control the conversation logic.</li><li>An embeddable ReactJS application that renders the chat toggle and the iframe. It normally is bundled as a <a href="https://github.com/umdjs/umd"><strong>UMD module</strong></a> with some auto-rendering logic on initialization (in our case, the logic renders a chat toggle button on the left or right of the page based on the provided configuration). The chat widget is also designed to be installed as a regular NPM package in case you want to import it into your ReactJS project directly.</li><li>A standalone ReactJS application rendered as a chat window in the iframe.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9_UgMqrI4VlbqJgU.png" /><figcaption>The Chat Widget Architecture</figcaption></figure><p>The widget applications use <a href="https://theme-ui.com/"><strong>Theme UI</strong></a> for styling. It provides a rich set of components that can be styled in the styled-components fashion. The result is that the styling is bundled along with other JS which is useful to keep widget.js self-contained without a need to request external CSS files. This way widget.js is as lightweight as possible and all heavy-lifting is done inside the chat window iframe.</p><p>Rendering the chat window application in an iframe has a few merits. Iframes isolate the chat window behavior and styles from the parent website’s assets. This helps to avoid styling clashes or rendering the website broken because of issues in the chat window. Apart from that, if there are any security vulnerabilities in the chat window application, it would be much harder to exploit them to harm the host website.</p><p>The chat window iframe is sandboxed with the following permissions:</p><ul><li>allow-scripts</li><li>allow-popups</li><li>allow-same-origin</li><li>allow-forms</li></ul><p>The chat window iframe also comes with some inconveniences as it’s isolated from the widget.js application just like from the other host website code, so any interactions between the chat widget and the chat window are more complicated and possible only via <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage"><strong>message event posting</strong></a>.</p><p>Because of these iframe specifics, the widget.js passes widget configurations to the chat window application via iframe URL query params along with other information like <a href="https://www.romaglushko.com/blog/papercups/#identify-widget-customers"><strong>customer metadata</strong></a> or the widget.js library version.</p><p>The Papercups/Browser is a vanilla JavaScript library that provides a singleton Papercups object with the whole conversation logic. The library doesn’t contain any ReactJS code or components. Instead, the other applications like the chat window inits it, subscribe to its events, and update their views in callbacks:</p><pre>export type Config = {<br>  accountId: string;<br>  customerId?: string | null;<br>  inboxId?: string;<br>  baseUrl?: string;<br>  greeting?: string;<br>  awayMessage?: string;<br>  customer?: CustomerMetadata;<br>  debug?: boolean;<br>  setInitialMessage?: (overrides?: Partial&lt;Message&gt;) =&gt; Array&lt;Message&gt;;<br>  onSetCustomerId?: (customerId: string | null) =&gt; void;<br>  onSetConversationId?: (conversationId: string) =&gt; void;<br>  onSetWidgetSettings?: (settings: WidgetSettings) =&gt; void;<br>  onPresenceSync?: (data: any) =&gt; void;<br>  onConversationCreated?: (customerId: string, data: any) =&gt; void;<br>  onMessageCreated?: (data: any) =&gt; void;<br>  onMessagesUpdated?: (messages: Array&lt;Message&gt;) =&gt; void;<br>};</pre><blockquote><strong><em>The logic in the shared library</em></strong></blockquote><blockquote>Separating the key logic into a library like that brings additional value.</blockquote><blockquote>If you don’t use ReactJS like Papercups official chat components, but use VueJS or SvelteJS, let’s say, you could still integrate it into your stack by following the same integration route they did in the original chat applications. It would be quicker than without the Papercups/Browser library as you would need to rewrite the rendering part only. The main conversation logic would reused from the library.</blockquote><p>The key state that the library maintains is the conversation messages. It’s just a plain JS array of message objects (not a ReactJS state) that are updated by the library. When an update happens, the library simply <a href="https://www.romaglushko.com/blog/papercups/#the-live-chatting"><strong>calls back</strong></a> the corresponding listeners.</p><h3>Widget Settings</h3><p>We have seen above that it’s possible to pass widget configurations via window.Papercups.config object. These configurations are defined and specified externally, we have no control over them.</p><p>Apart from that, during setting up a new live widget, you can build the desired config right from the Papercups UI. When that happens, Papercups saves the settings on the account_id and inbox_id levels. These settings serve as defaults for the corresponding chat widget instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b5FRcls9hh0n7m40.png" /><figcaption>The Chat Widget Settings Builder</figcaption></figure><p>On chat widget initialization, the widget tries to combine the configurations provided in the window object with the widget settings fetched from the backend. Then the combined settings are passed into the chat window iframe via URL query params.</p><p>Along the way, the chat widget sends a request to update widget metadata which consists of hostname, path, last_seen_at where the widget instance was seen. It’s used for analytics purpose.</p><figure><img alt="The Chat Widget Settings Lifecycle" src="https://cdn-images-1.medium.com/max/1024/0*TOOEAcUgCfY17_aU.png" /><figcaption>The Chat Widget Settings Lifecycle</figcaption></figure><p>The chat window renders the window content according to the passed config. It also inits the Papercups object that additionally fetches widget settings, but they don’t seem to be used much (although this specific workflow would be helpful if you used the library directly).</p><p>The chat widget can be also installed as an NPM package and imported directly into a ReactJS project. For that specific use case, the widget supports the config:update message event that is posted to the chat window iframe to help the widget component properly update widget settings on change.</p><p>The widget settings API is used as an enforcement for the Papercups chat branding. If you are not on the team subscription plan, then you cannot disable Papercups branding, but if you are, you may disable or keep it.</p><blockquote><strong><em>Chat Widget Security</em></strong></blockquote><blockquote>The requests to the widget settings API are a basic validation that the given account_id and inbox_id pair exist. That said, someone could still copy-paste the correct config from another website to add the chat widget to an unauthorized website. Papercups did not really get to solving this widget abuse problem, but it’s still worth mentioning our options.</blockquote><blockquote>Typically, you would like to have a list of authorized websites where you expect to install the widget. Then, the widget itself may check whether the current window.location is in the allow list or fails to load. Finally, you may consider sending CSP headers (like <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors"><strong>frame-ancestors</strong></a>) whitelisting only the authorized websites to embed the widget.</blockquote><h3>Identify Widget Customers</h3><p>There are likely better ways to do it (e.g. using cookies), but Papercups goes super simple about customer identification in the live conversations.</p><p>First of all, the host website has an option to specify customer information as a part of the window.Papercups.config:</p><pre>&lt;script&gt;<br>window.Papercups = {<br>  config: {<br>    // ...<br>    customer: {<br>        name: __CUSTOMER__.name,<br>        email: __CUSTOMER__.email,<br>        external_id: __CUSTOMER__.id,<br>        metadata: {<br>            plan: &quot;premium&quot;<br>        }<br>    }<br>  },<br>};<br>&lt;/script&gt;</pre><p>If you happen to deal with an authenticated customer session, this is a way to share that bit of context with Papercups.</p><p>Other than that, the chat widget and the chat window try to find an existing customer ID in the local storage and collect the basic information about Customer like OS, browser, screen resolution, time zone, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sdBGPMf1ZXNPPkME.png" /><figcaption>The Chat Widget Customer Identification</figcaption></figure><p>If there is a customer ID in the local storage, we validate if the Papercups API knows about this ID and if it belongs to the current Account. If not, we try to find a customer by hostname, email, external ID.</p><p>If we fail to do that, we create a new Customer under the given Account. Otherwise, we update the existing customer metadata and persist its ID in the local storage.</p><h3>The Live Chatting</h3><p>Yet again, we have a need to identify a conversation, but now it’s in the live chat setup. It would not be cool to miss the whole conversation when the browser tab was closed or reloaded. Papercups goes simple about this and fetches the latest open chat conversation for the specific customer_id, account_id, and inbox_id. The customer_id is persisted in the local storage, so it was set once anywhere it would be available to the chat widget.</p><p>For all real-time interactions, Papercups uses <a href="https://hexdocs.pm/phoenix/channels.html"><strong>Phoenix Channels</strong></a>. Phoenix Channels uses websocket as transport and establishes bi-directional communication channels between Customers and agent Users.</p><blockquote><strong><em>Phoenix Channels and Multi-replica Deployments</em></strong></blockquote><blockquote>The cool thing about Phoenix Channels is that they work even when there are a few replicas of the channel backend server. This means that you need no additional services like Redis by default to make the chat widget, for example, work in the Kubernetes environment where microservices are deployed as a few instances and then resized based on the load.</blockquote><blockquote>This is possible thanks to <a href="https://www.erlang.org/doc/apps/kernel/pg.html"><strong>the pg library</strong></a> which stands for Process Group. The pg implements a typical cluster membership protocol that connects multiple distributed processes and lets them send messages to each other.</blockquote><p>There are three channels that each Customer joins while interacting with the live chat:</p><ul><li>Conversation Channel (e.g. conversation:{conversation_id}) - The channel where all messages for the given conversation are broadcasted. The live chat joins them when the last conversation is identified or a new one is created.</li><li>Conversation Lobby Channel (e.g. conversation:lobby:{customer_id}) - The channel through which Customer is notified about a new conversation. The agent User can start a new conversation with the Customer this way.</li><li>Account Room Channel (e.g. room:{account_id}) - Broadcast availability of the agents from the given Account.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*56y_h7nBouK6mwG4.png" /><figcaption>The Chat Widget Channels</figcaption></figure><p>The conversation is either fetched from the backend or created upon a new message from Customer. The list of conversation messages are handled by the Papercups/Browser library and not by the chat window application. The library updates its internal messages state and then executes callbacks like onMessagesChanged to notify the chat window application to rerender the chat window. The chat window sets the new messages to its ReactJS state and that rerenders the chat window.</p><p>When Customer sends a new message, the message gets added to the messages list and then send to the conversation channel as a shout event. Then, the server processes and saves the message and echoes it back with an updated metadata into the same channel. This is used as a way to ensure the message is acknowledged and saved.</p><p>The conversation lobby channel is a way to initialize a new conversation by User (for example, from <a href="https://www.romaglushko.com/blog/papercups/#storytime"><strong>the storytime session view</strong></a>). When that happens, the library switches the live chat to another conversation.</p><p>The account room channel is used to broadcast the agent availability status. It’s fully powered by <a href="https://hexdocs.pm/phoenix/presence.html"><strong>the Phoenix Presence functionality</strong></a>.</p><h3>The Message Seen or Not?</h3><p>Finally, the chat widget tries to keep track of messages that Customer has already seen or not. When a new agent message arrives, the chat window application figures out if Customer is looking at the chat widget or not. This is done as a check to the widget toggle state (open or not?) and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/hidden"><strong>the browsers document.hidden API</strong></a>. If the message was received but the chat window had been closed or the host website tab had not been active, the chat window plays a notification sound to bring attention back to the chat.</p><p>In addition to this, the chat window application listens to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event"><strong>the visibilitychange event</strong></a> to find out when the tab is active again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uIJc06rUiu_En0Yb.png" /><figcaption>The Chat Messages Visibility Tracking</figcaption></figure><p>Once Customer has seen the messages, the chat window application sends the messages:seen event to the conversation channel, so the backend marks the agent’s messages as seen, too.</p><h3>Reply Channels</h3><p><a href="https://www.romaglushko.com/blog/papercups/#email-forwarding"><strong>Email forwarding</strong></a>, <a href="https://www.romaglushko.com/blog/papercups/#sms"><strong>SMS</strong></a>, <a href="https://www.romaglushko.com/blog/papercups/#gmail-sync"><strong>Gmail thread sync</strong></a>, and <a href="https://www.romaglushko.com/blog/papercups/#live-chat-widget"><strong>live chat widget</strong></a> are message source channels that populate Papercups’ Inboxes.</p><p>There is another type of channels called reply channels. Reply channels are a handy way to reply to Papercups’ Conversations right from your <a href="https://slack.com/"><strong>Slack</strong></a> or <a href="https://mattermost.com/"><strong>Mattermost</strong></a> spaces. Both Slack and Mattermost integrations are conceptually similar, so we will focus on the Slack only.</p><p>The platform supports Slack thread syncing (just like <a href="https://www.romaglushko.com/blog/papercups/#gmail-sync"><strong>Gmail thread syncing</strong></a>) and handles Conversations right from the Slack threads. Both functionalities require authorizing Papercups to work with your Slack workspace.</p><p>The Slack supports <a href="https://api.slack.com/messaging/webhooks#oauth_response"><strong>the OAuth2 authorization workflow</strong></a> just like Gmail. Papercups requests quite a few scopes to work with Slack channels, private groups, chat messages, message files, reactions, and Slack user info. Once the authorization is done, Papercups saves the access_token, bot, team, webhook information, etc. as a separate SlackAuthorization entity.</p><p>Then, the User has to invite the Papercups Bot application into the needed channels to finish the setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XJTYSQQIBSaXxPyV.png" /><figcaption>The Slack Integration</figcaption></figure><p>After this, the platform will start receiving various Slack events via webhook calls. The key event is when a new message is added to the channel or private group. Papercups identifies if the new message is from the channel associated with the reply type and then loads the corresponding Conversation via metadata stored in the SlackConversationThread (similar to GmailConversationThreads) to create a new Message there.</p><p>Otherwise, the message is assumed to be from a support channel and Papercups performs sync of messages in this Slack thread if it’s known or creates a new SlackConversationThread if not.</p><h3>Storytime</h3><p>The Papercups use cases revolve round customer support. Imagine a situation where a customer has a problem filling in a form. Would not it be nice to see what customer was actually doing and how they were trying to submit the form? Papercups has an experimental support for this sort of functionality called Storytime.</p><p>Storytime is essentially a browser session tracking library that is bundled as a separate embedded JavaScript file. It uses the window.Papercups.configs info to seamlessly integrate with host websites that are already using <a href="https://www.romaglushko.com/blog/papercups/#live-chat-widget"><strong>the Papercups live chat widget</strong></a>.</p><p>The Storytime operates on two key concepts: browser sessions and browser replay events.</p><p>Browser sessions are a way to track the activity of a specific tab or window when Customers browse the host website. When they do that, Customers emits a various replay events that Papercups collects and replays for Users in the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*62LPL-Mf3V1ORS3x.png" /><figcaption>The Papercups Browser Sessions Data Model</figcaption></figure><p>On initialization, the Storytime script tries to find out if there is any existing browser session stored in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage"><strong>window.sessionStorage</strong></a>. If the session exists, it validates its ID and restarts which simply means resetting the browser session finish_at timestamp. Then, Storytime updates the customer metadata of the session.</p><p>If there is no session, Storytime starts a new one and stores it in the window.sessionStorage. Interestingly, the start request is done as <a href="https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API"><strong>a beacon request</strong></a>.</p><p>After that, Storytime does only two things:</p><ul><li>Tracks activity of the current tab to emit session:active and session:inactive events (rendered on the session listing page to indicate if anything is going on in those sessions).</li><li>Watch for customer activity on the page via <a href="https://www.romaglushko.com/blog/papercups/rrweb.io/"><strong>rrweb</strong></a> library and emit replay:event:emitted events.</li></ul><p>All these events go into one browser session events channel (e.g. events:{account_id}:{session_id}). The browser events are stored then into database (to replay them when the session is over).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0YqohrjkfYnkV6T6.png" /><figcaption>The Storytime In Action</figcaption></figure><p>On the dashboard end, Users actually connects to two channels:</p><ul><li>The browser session events channel to receive and replay events in real time</li><li>The account browser session events channel (e.g. events:admin:{account_id}) to receive updates about sessions’ statuses.</li></ul><p>Storytime heavily uses Phoenix Presence. If no Users are watching events of a specific browser session, Papercups don’t record them. Also, it updates presence metadata to reflect session activity in the all browser sessions channel.</p><p>Storytime listens to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event"><strong>beforeunload</strong></a> event and sends another beacon request to finish the session.</p><h3>Webhooks &amp; Functions</h3><p>Papercups owns an important piece of information about organization’s customer interactions. It’s very natural that some of them would like to implement additional automations on top of the existing Papercups functionality.</p><p>For example, when a new customer message arrives, we may want to show it to our LLM agent to see if it can respond meaningfully without involving the support team.</p><p>In order to achieve that, the platform provides an ability to subscribe to conversation events and trigger some functions when the events occur.</p><h3>Subscribe to Events</h3><p>The webhook functionality looks very simple. There is a way to add a new webhook HTTP endpoint which must be accessible by the platform.</p><p>On webhook registration, Papercups sends a verification request to the endpoint. The platform sends it a random 64-char token and expects it to be echoed back.</p><p>All verified webhooks are eligible to receive real events.</p><p>Papercups defined only two events: conversation:created and message:created. The event names serve as a scope for webhooks, so you may decide what events to receive.</p><h3>Functions</h3><p>The functions are event handlers that are deployed as serverless functions. Serverless functions are a very good cost-efficient alternative to webhooks that don’t require any infrastructure maintenance and well-suited for ad-hoc nimble automation.</p><p>Papercups uses <a href="https://aws.amazon.com/lambda/"><strong>AWS Lambda</strong></a> as a serverless function backend behind their function API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hEzDZ5fOQyooKYQ7.png" /><figcaption>The Function Editing</figcaption></figure><p>The typical function receives a Papercups event, inspects it and does a request back to Papercups Public API or elsewhere.</p><p>That’s easier to say than to do, because to do that from a serverless function, you need:</p><ul><li>authenticate your request</li><li>do a request in a nice way e.g. via Papercups client library</li></ul><p>When User is done editing the function code, the Dashboard UI packs the function code (e.g. putting it in index.js) along with the content of deps.zip served by the Papercups server. The deps.zip contains additional node_modules dependencies that the function needs to run including the Papercups client library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m9MTjbAn4LaIxGuk.png" /><figcaption>The Function Creation Workflow</figcaption></figure><p>The backend receives the updated zip file and uploads it to a separate AWS S3 bucket that holds all the function codes. The unique function name is used as a S3 object key.</p><p>Finally, the backend creates a new Lambda function referencing the files uploaded to the AWS S3 bucket. Along with the code reference, Papercups specifies:</p><ul><li>Runtime (e.g. NodeJS of the needed version)</li><li>Event handler (e.g. index.handler)</li><li>AWS ARN role to limit exposure of AWS functionality to functions</li><li>Environment variables with the Papercups API key to seamlessly allow accessing the public API</li></ul><p>That’s it. The function is ready to be invoked on events which involves calling one more AWS API with event payload.</p><h3>Reporting &amp; Analytics</h3><p>Papercups has two types of reporting:</p><ul><li>the account-wide reporting to track how well the support team engages with customer requests</li><li>platform-wide reporting used to check the overall growth of the product</li></ul><h3>Account Reporting</h3><p>The account-level engagement reports consist of simple aggregative statistics like:</p><ul><li>the number of messages and conversations</li><li>the number of messages per User</li><li>the number of messages per weekday</li><li>the number of messages sent and received</li></ul><p>All these statistics are calculated per each day of the given time range.</p><figure><img alt="The Papercups Account Reporting" src="https://cdn-images-1.medium.com/max/1024/0*VUuPJIR0PlCbu1GF.png" /><figcaption>The Papercups Account Reporting</figcaption></figure><p>There are two more customer service-specific metrics you want to track too:</p><ul><li>how long does it take for customers to receive the first reply to their conversations?</li><li>how long does it take to resolve the conversation?</li></ul><p>You typically want to minimize both.</p><p>The time to first reply is one of the key metrics in the customer service business. The quicker you pick your phone, the happier your customers are. The metric improves customer loyalty and reduces frustration.</p><p>The time to resolve measures the efficiency and quality of your support team. Quicker resolution also means happier customers. On the operational side of things, time to resolution helps to better plan for the support team’s capacity.</p><p>For each of these metrics, Papercups calculates the average and mean time.</p><h3>Platform Reporting</h3><p>The platform reporting is a completely internal statistics. Papercups collects it once a week and sends it over Slack.</p><p>The internal metrics are calculated for:</p><ul><li>this week,</li><li>the previous one,</li><li>the all-time total.</li></ul><p>There are growth metrics like:</p><ul><li>the number of new accounts</li><li>the number of new users</li><li>the number of new customers</li><li>the number of new messages</li><li>the top 4 the most active accounts (e.g. ranked by message count)</li><li>the top 4 the most active users (e.g. ranked by message count)</li><li>the platform MRR is based on Stripe subscriptions</li></ul><p>Another batch of metrics measures the usage of different functionality:</p><ul><li>the number of new messages grouped by source (e.g. email, SMS, live chat, etc.)</li><li>the number of conversations per source</li><li>the number of widget installations</li><li>the number of new integrations enabled per type (e.g. Gmail, Slack, Mattermost, etc.)</li><li>the top 4 accounts with the most customers</li></ul><h3>Other Notifications</h3><p>Papercups uses the same Slack messaging approach to notify about:</p><ul><li>new subscriptions or subscription cancelling</li><li>new account registration</li></ul><h3>Summary</h3><p>Time to wrap it up.</p><p>We have reviewed the ins and outs of a customer service platform called Papercups. The product side of the platform, their billing, data organization, and the most interesting technical details of working with all six communication channels it supports.</p><p>On the UI side, we have gone through the implementations of the embedded live chat and storytime analytics.</p><p>Papercups is a great example of a feature-full SaaS platform done in a radically simple way. A big part of that success should be attributed to using Elixir and Phoenix Framework that do so much for so little effort.</p><p>If you enjoyed this deep dive, be sure to let me know and share it broadly.</p><blockquote>The original article was posted on <a href="https://www.romaglushko.com/blog/papercups/">my website</a>. Go and check it out 👀</blockquote><h3>References</h3><ul><li><a href="https://github.com/papercups-io/papercups"><strong>[GitHub] Papercups Backend</strong></a></li><li><a href="https://github.com/papercups-io/chat-widget"><strong>[GitHub] Papercups Live Widget</strong></a></li><li><a href="https://github.com/papercups-io/storytime/tree/master"><strong>[GitHub] Papercups Storytime</strong></a></li><li><a href="https://github.com/papercups-io/charts"><strong>[GitHub] Papercups Chart</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65fa71eb2e25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenTelemetry Collector]]></title>
            <link>https://roma-glushko.medium.com/opentelemetry-collector-architecture-cce94d40a7e1?source=rss-2607aea71af1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cce94d40a7e1</guid>
            <category><![CDATA[opentelemetry-collector]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <dc:creator><![CDATA[Roma Glushko ]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 10:56:51 GMT</pubDate>
            <atom:updated>2024-08-09T10:56:51.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QQnCLIXUwOMjTPkr.jpg" /><figcaption>Photo by <a href="https://unsplash.com/@ansleycreative"><strong>Unsplash</strong></a></figcaption></figure><p>The OpenTelemetry Collector is designed to offload observability processing to a separate service, distancing it from the applications that generate the observability data. By doing so, applications can remain streamlined, focusing solely on their core functionality, while the advanced signal processing logic is centralized and shared across all services in the system.</p><p>Today, we will explore how such services can be implemented.</p><blockquote><em>The original article was posted on </em><a href="https://www.romaglushko.com/blog/opentelemetry-collector/"><em>my website</em></a><em>. Go and check it out 👀</em></blockquote><p>This article is a part of my OpenTelemetry series:</p><ul><li><a href="https://medium.com/@roma-glushko/opentelemetry-sdk-design-e378101b1612">OpenTelemetry SDK: Concepts &amp; Design</a></li><li>OpenTelemetry Collector: Architecture (this one)</li></ul><h3>OTel Collector</h3><p>In the previous article about <a href="https://www.romaglushko.com/blog/opentelemetry-sdk/"><strong>the trace, metrics, log pipelines in the OTel SDK part</strong></a>, we briefly touched on exporters at the end of the pipelines. While OpenTelemetry SDK does support a limited number of exporters like OTel-compatible backends, Jeager or Zipkin (for traces), and Prometheus (for metrics), it’s recommended to send all signals out of your services as soon as possible to do all needed signal processing in the OTel Collector.</p><p>The OpenTelemetry Collector acts as an additional layer of indirection that protects your business services from changes in observability backends since your services are exposed only to the collector.</p><p>The Collector makes life easier for your business services by taking over the heavy lifting of collecting observability data. This includes batching, sampling, cleaning, and finally, exporting the data to various backends. By offloading these tasks to a vendor-neutral service, your code stays cleaner and more focused.</p><p>Think of it like using a database, a queue or an API gateway. Each of these offloads some responsibilities from your services making them simpler in the end. Just like in those cases, deploying the collector might add complexity to your system since there’s one more piece to maintain.</p><h3>Architecture</h3><p>The high-level architecture of the OTel Collector is somewhat similar to the SDK trace design. The collector consists of three uniform signal processing pipelines per each signal type.</p><figure><img alt="The OTel Collector Architecture" src="https://cdn-images-1.medium.com/max/1024/0*yMJn3-TK1Z0z0JxZ.png" /><figcaption>The OTel Collector Architecture</figcaption></figure><p>Each pipeline, in turn, is made up of three stages:</p><ul><li><strong>Receiving</strong>. The receiver components accept the signals from external data sources.</li><li><strong>Processing</strong>. The processor components can do all sorts of preprocessing like batching, filtering, attribute reduction, etc.</li><li><strong>Exporting</strong>. The exporter components fan out processed data into observability backends.</li></ul><p>There are also connector components that can connect the end of one pipeline with the beginning of another. This allows the use of pipeline output as a source of signal for another pipeline.</p><p>It’s cool to note that all of these pipelines can be dynamically put together based on <a href="https://www.romaglushko.com/blog/opentelemetry-collector/#the-collector-config"><strong>the Collector’s config</strong></a>.</p><h3>Configuration</h3><p>The OTel Collector’s config is <a href="https://yaml.org/"><strong>a YAML file</strong></a> and its structure is tied to the service architecture to make it easier to understand it and reason about. There are sections like receivers, processors, exporters and a service that connects them all together allowing to define service.pipelines:</p><pre>receivers:<br>  otlp:<br>    protocols:<br>      grpc:<br>        endpoint: localhost:4317<br> <br>processors:<br>    memory_limiter:<br>    batch:<br> <br>exporters:<br>    jaeger:<br>    datadog:<br> <br>service:<br>  pipelines:<br>    traces:  # a default trace pipeline<br>      receivers: [otlp]<br>      processors: [memory_limiter, batch]<br>      exporters: [jaeger]<br>    traces/datadog:  # another trace pipeline<br>      receivers: [otlp]<br>      processors: [batch]<br>      exporters: [datadog]</pre><p>Each component type is possible to define separately outside of the pipeline definition to be able to be reused in multiple pipelines without copy-pasting its definitions.</p><p>Components have IDs in a special format type/name like traces/datadog, batch, or otlp in the sample config above. The name can be empty which is nice if you don’t have many instances of the same component type.</p><p>The config itself can be loaded from multiple sources:</p><ul><li>Environment variable</li><li>YAML file</li><li>YAML string</li><li>External HTTP(S) URL</li></ul><p>All sources are merged together to get an effective configuration. Along the way, the OTel Collector expands environment variables in the config content like $ENV_VAR. This allows you to keep sensitive information outside of the general config that you may take under git version control.</p><h3>Pipelines</h3><p>After loading and merging the config, the collector gets to work on building the defined pipelines and their related components.</p><p>Given that all service layouts are fully dynamic, we don’t know the order in which to build, start, and stop the pipeline’s components ahead of time. To address that, the collector represents the pipeline configuration as a directed acyclic graph (DAG). It then performs <a href="https://cp-algorithms.com/graph/topological-sort.html"><strong>topological sorting</strong></a> on the graph to get the right order, considering dependencies between the pipeline components.</p><figure><img alt="An example of Pipeline Graph" src="https://cdn-images-1.medium.com/max/1024/0*b7aprs-guaqssmsm.png" /><figcaption>An example of Pipeline Graph</figcaption></figure><p>In addition to nodes corresponding to consumers we’ve already seen (e.g. receivers, processors, exporters), each pipeline graph also includes two more “virtual” node types:</p><ul><li>The Capability node is the first data consumer in every pipeline and effectively represents whether a pipeline has any processors that would mutate incoming observability signals. Not having that bit of context, we would have to assume that all pipelines mutate their data. That would prevent us from having some of the low level memory usage optimizations that the FanOut node does.</li><li>The FanOut node performs “smart routing” of incoming signal data. It’s typically used after receivers and before exporting state. It sends copies of original data to all consumers (e.g. the first processor in a pipeline or an exporter) that mutates data and then uses the original copy to send it to all consumers that don’t change the incoming structure. This saves us from unneeded memory allocations and eliminates issues related to concurrent modifications of the same data from multiple consumers. For example, a few exporters can process and export the same data at different paces affecting each other’s work.</li></ul><h3>Receivers</h3><p>As the name suggests, receivers accept observability signals and trigger the processing pipeline.</p><p>The OTel Collector provides HTTP- and gRPC-based receivers out of the box. Since the OTel protocol uses a push model, the OTel receiver simply starts a regular HTTP or gRPC server and waits for instrumented services to connect.</p><p>In addition to the OTel format, the collector could be configured to accept signals in <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/jaegerreceiver"><strong>Jaeger</strong></a>, <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/zipkinreceiver"><strong>Zipkin</strong></a>, AWS X-Ray, StatsD, Prometheus protocols.</p><p>Moreover, signals can be received from message queues like <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/kafkareceiver"><strong>Apache Kafka</strong></a>, GCP PubSub, Azure EventHub, etc.</p><p>Not all systems natively speak the OTel protocol, so some receivers can extract useful statistics from various systems and convert them into OTel signals. This includes Redis, MongoDB, RabbitMQ, NGINX, PostgreSQL, and <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver"><strong>many others</strong></a>.</p><h3>Metrics Scrapping</h3><p>Specifically for metrics, in addition to the OpenTelemetry push-based metrics collection, the collector supports Prometheus-like data scraping (e.g. the pull model).</p><figure><img alt="The Scraper Controller" src="https://cdn-images-1.medium.com/max/1024/0*2VaV1V42AQ3_OYim.png" /><figcaption>The Scraper Controller</figcaption></figure><p>The collector scrapping architecture consists of ScraperContoller which manages a set of configured scrapers. The ScraperContoller maintains a ticker one for all scrapers that initializes the beginning of scrapping. All scrapers collect and return metrics (as OTel metric data structs) that in turn get batched. The batch is used to start all processing pipelines scrappers connected to. The whole scrapping process can be limited in time via context’s timeout.</p><h3>Processors</h3><p>Processors are the most “logic-rich” part of pipelines that can do all sorts of modifications on the incoming signal batches, such as:</p><ul><li>sampling or filtering data,</li><li>batching,</li><li>rejecting or retrying batches,</li><li>so on.</li></ul><p>A set of processors in a pipeline forms a processing chain, so the first processor gets data earlier than others, may modify it, and send it further to the second processor, and so on. This way, the order in which processors are defined in a pipeline is super important. Effectively, this means that filtering and sampling should be defined closer to the beginning of pipelines while something like batching typically goes in the middle or the end of pipelines.</p><h4>Memory Limiter</h4><p>One of the default processors that comes with the OTel collector is the memory limiter processor. The collector handles a ton of data, and the amount of data and resources it can use vary a lot depending on the system generating the data. Because of this, the collector is a memory-bound service that can easily run out-of-memory (OOM) if it’s not setup correctly. The memory limiter is a clever engineering solution to help prevent these issues.</p><figure><img alt="The Memory Limiter Workflow" src="https://cdn-images-1.medium.com/max/1024/0*yBfsquwQi9MNlAV9.png" /><figcaption>The Memory Limiter Workflow</figcaption></figure><p>The memory limiter checks service memory usage periodically and sees if the usage goes above any of the defined limits:</p><ul><li>The soft memory usage limit (or the spike limit). If memory usage goes beyond the soft limit, the collector starts to shed load and reject all incoming data.</li><li>The hard memory usage limit. If memory usage goes above the hard limit, the collector immediately calls Golang <a href="https://pkg.go.dev/runtime#GC"><strong>runtime.GC()</strong></a> to hopefully reclaim enough memory to start accepting data again. Garbage collection is not a cheap operation, so additionally make sure it’s not done more frequently than once in 10 seconds.</li></ul><p>The memory limiter can be seen as a way to add back pressure to the collector, so it’s harder to overload the service. Although this requires receivers and signal producers to handle data rejections gracefully which normally boils down to retries with backoff.</p><blockquote><strong><em>GOMEMLIMIT</em></strong></blockquote><blockquote>The OTel Collector Helm Chart allows to set <a href="https://pkg.go.dev/runtime#hdr-Environment_Variables"><strong>the GOMEMLIMIT environment variable</strong></a> (available since Go 1.19+) additionally to the memory limiter. The variable limits the maximum amount of heap memory a Golang process can occupy. That acknowledges Go runtime with a useful context and mitigates OOM situations to a good extent in general.</blockquote><h4>Batch Processor</h4><p>The batch processor looks a lot like <a href="https://www.romaglushko.com/blog/opentelemetry-sdk/#span-processors"><strong>SpanProcessor from OTel SDK</strong></a> but it can process all three types of signals. Similarly, the collector’s batching is bounded by batch size and timeout.</p><p>Unlike SpanProcessor, the batch processor supports sharding data by client metadata enabling OTel collector to process data in a multi-tenant way.</p><figure><img alt="The OTel Collector Batch Processor" src="https://cdn-images-1.medium.com/max/1024/0*fs6WwbajtZqzrY0H.png" /><figcaption>The OTel Collector Batch Processor</figcaption></figure><p>Each shard will hold information for a specific tenant which makes it easier to export to store separately. For example, Grafana’s LGTM stack <a href="https://grafana.com/docs/loki/latest/operations/multi-tenancy/#multi-tenancy"><strong>supports</strong></a> multi-tenant data storage and processing. All you gotta do is to pass the X-Scope-OrgID along with your requests.</p><blockquote>The default the OTel Collector functionality may not be enough though to close multi-tenant scenarios and you may need to install a contrib extension called <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/headerssetterextension"><strong>headersetter</strong></a> to get there.</blockquote><h3>Exporters</h3><p>Exporters handles batches prepared by processors. Internally, these exporters are structured as pipelines, too, each equipped with a series of sender components designed to ensure the reliable export of signal batches:</p><ul><li><strong>Queue sender</strong> enqueues incoming batches to be sent further according to a specified parallelism (e.g. determined by the number of queue consumers) to the next stages of the sending pipeline.</li><li><strong>Retry sender</strong> uses exponential retry with backoff to try sending batches in case of errors. Interestingly, the OTel Collector doesn’t cap the maximum number of retries but rather limits the total time the batch was trying to be exported.</li><li><strong>Timeout sender</strong> limits the time the collector waits for successful signal accepting on the observability backend side.</li><li><strong>Pusher stage</strong>. The final stage of the sending pipeline, where either an HTTP or gRPC request is made to the observability backend.</li></ul><figure><img alt="The exporter pipeline" src="https://cdn-images-1.medium.com/max/1024/0*6xLMDHPyacBq7NmC.png" /><figcaption>The exporter pipeline</figcaption></figure><h4>Export Queues</h4><p>The Queue Sender can be configured to use:</p><ul><li>Simple bounded in-memory queue. It rejects new batches as long as its capacity is full. As a data structure for the queue, OTel uses <a href="https://go101.org/article/channel.html"><strong>a Go’s channel</strong></a> with a predefined capacity.</li><li>Or a persistent queue that stores items on disk.</li></ul><p>Let’s dive a bit into how data persisting is actually implemented.</p><p>The storage used to persist queue items is provided via <a href="https://www.romaglushko.com/blog/opentelemetry-collector/#extensions"><strong>special extension type</strong></a>. The storage extension interface resembles a simple key-value database interface:</p><ul><li>it supports get(), set(), delete() value by key</li><li>additionally, it allows to batch() these operations which is a form of transactions</li></ul><p>Using that interface, the OTel Collector organizes processing this way:</p><ul><li>Each signal batch is stored as a value under an incremental key.</li><li>The collector persists writeIndex and readIndex to know what is the next batch index to use or to dispatch and tries to export correspondingly. The dispatched items are persisted too.</li><li>If a batch has been successfully exported, it will be removed from the storage.</li></ul><figure><img alt="Processing of a file-store-based queue" src="https://cdn-images-1.medium.com/max/1024/0*YODSrmiDFbsWN_Mo.png" /><figcaption>Processing of a file-store-based queue</figcaption></figure><p>As of now, the OTel Collector provides storage implementations based on <a href="https://pkg.go.dev/go.etcd.io/bbolt"><strong>bbolt</strong></a>, SQLite and PostgreSQL (all are available as contrib extensions).</p><h3>Observability</h3><p>This is no surprise but the OTel Collector requires some observability on its own, too.</p><p>First of all, the collector allows to pass <a href="https://opentelemetry.io/docs/specs/otel/overview/#resources"><strong>the Resource attributes</strong></a> as key-value data, so you can override the way the collector deployment is represented on your observability platform. Also, you can pass additional attributes associated with the collector that are going to be attached to all observability signals.</p><h4>Logging</h4><p>For logging, the collector uses <a href="https://github.com/uber-go/zap"><strong>Uber’s zap</strong></a>, a popular high-performance logging library. Besides common configs like log_level or encoding (e.g. JSON, a human-readable console format), the collector exposes:</p><ul><li><a href="https://pkg.go.dev/go.uber.org/zap#Config"><strong>the initial fields config</strong></a> that is useful to label all logs with some metadata like team or owner.</li><li><a href="https://pkg.go.dev/go.uber.org/zap/zapcore#NewSamplerWithOptions"><strong>log sampling</strong></a>. The sampler tracks log records with the same level and message and can make sure only N records are logged in a period of time. After that, it will either drop all remaining records in that time window or log one in M records. This is a great way to keep representative logs while managing the general log volume. As a result, sampling helps to relax CPU and I/O load as well as reduce the cost of storing generated log data.</li></ul><h4>Metrics</h4><p>Just like with logging, the collector offers three levels of metrics collection:</p><ul><li>none - no metrics will be collected.</li><li>basic - the recommended option that covers the basics of collector functioning.</li><li>detailed - besides doing metric measurements, it also logs OTel structures for debugging purposes.</li></ul><p>There is a separate feature gate that filters out metric attributes that can potentially cause the high cardinality problem. The filtering is done via <a href="https://www.romaglushko.com/blog/opentelemetry-sdk/#views--aggregations"><strong>metric views</strong></a> that help to configure aggregations around metric measurements and, what is crucial for our case, it can drop some data points along the way. Specifically, the collector drops attributes in its gRPC and HTTP API instrumentations:</p><ul><li>Hostname and port number</li><li>Local socket address and port number</li></ul><blockquote><strong><em>Cardinality Explosion</em></strong></blockquote><blockquote>Let’s say you have a metric customer_logged_in with these attributes:</blockquote><blockquote>user_id &amp; org_id - MongoDB ObjectIDs of customers and their orgs</blockquote><blockquote>ip_addr - customer’s IP address</blockquote><blockquote>What is the set of possible values for each of these attributes? It’s so big that we can say it’s virtually unbound.</blockquote><blockquote>The overall cardinality of the metric is even bigger because it’s multiplication of cardinalities of each metric attribute (it’s essentially a number of members called data points in a set with user_id x org_id x ip_addr axis).</blockquote><blockquote>Metrics like that can produce many data points that observability backends begin to struggle to operate on. They start to process queries slower, take more resources and eventually bill you much more.</blockquote><blockquote>This is a classic problem in the observability space (and not only there but also in Machine Learning, analytics and other areas where people work with multi-dimensional data) and it’s called <strong>cardinality explosion</strong>.</blockquote><blockquote>If a metric has attributes with potentially unbound value sets that are small right now, it can grow over time and explode at some point, too.</blockquote><blockquote>Typically, there are a few approaches to cope with this problem that include:</blockquote><blockquote>simply dropping high cardinality attributes (or even the whole metric) like the OTel Collector does</blockquote><blockquote>squeezing the high cardinality metric into categories with a much smaller number of values (for example, ip_addr could be represented as country or continent)</blockquote><p>Now let’s take a deeper look at the collector’s conventions around metrics and what it’s actually trying to measure.</p><p>All dynamic pipeline components have some well-defined metrics to measure on top of metrics custom components may decide to record additionally under the hood. Pre-defined metrics are scoped with component prefixes like receiver/, scraper/, processor/, and exporter/. If some operations like span export can end up with success or different failures, the OTel collector measures them as distinct metrics. For example:</p><ul><li>exporter/sent_spans - a counter that tracks spans exported successfully</li><li>exporter/send_failed_spans - a counter that tracks failed to be sent by exporter</li><li>exporter/enqueue_failed_spans - a counter that tracks failures related to queuing spans e.g. the queue is full</li></ul><p>Such separation helps to plot this data and attach some state-specific context as attributes.</p><p>All three sets of metrics contain component ID (like exporter ID) information in attributes.</p><p>Other than that, the collector measures in-process stats periodically (not more frequently than once per second):</p><ul><li>process_uptime (in seconds)</li><li>process_runtime_heap_alloc_bytes - memory occupied by referenced and unreferenced (not yet swept) heap objects</li><li>process_runtime_total_alloc_bytes - cumulative (only increases and doesn’t decrease after garbage collection) version of the metric above</li><li>process_runtime_total_sys_memory_bytes - virtual memory allocated by Go runtime (from the OS perspective)</li><li>process_cpu_seconds - total CPU time (user and system combined)</li><li>process_memory_rss - total physical memory allocated (RSS)</li></ul><h4>Tracing</h4><p>The tracing part of the collector looks very standard. The collector exposes span processor and context propagator (<a href="https://www.romaglushko.com/blog/opentelemetry-sdk/#ctx-propagation"><strong>Trace Context</strong></a> and <a href="https://github.com/openzipkin/b3-propagation"><strong>Zipkin’s B3</strong></a> supported) configs. Those span processors are components from OTel Golang SDK and have nothing to do with the collector’s data processing pipelines (The OTel Collector, basically, acts as any other service instrumented with OpenTelemetry SDK).</p><p>Not absolutely every workflow is covered by traces. Only receiving and exporting parts of data pipelines and rather on the high level (of course, custom components can do their own tracing).</p><p>In receiver context, there may be long-lived contexts associated with gRPC streams, for example, so they outlive several data ingestions that come via that stream. In such cases, the collector doesn’t use that context to start a new trace (to be able to end it correctly later), but rather:</p><ul><li>uses context.Background() to create a new root span on it. If the long-lived context has any span context, it will be <a href="https://opentelemetry.io/docs/concepts/signals/traces/#span-links"><strong>linked</strong></a> with the newly created span.</li><li>puts the new span into the copy of the long-lived context and returns that.</li></ul><h3>Extensions</h3><p>Extensions expand the collector’s functionality that doesn’t work directly with signal data. A great example of that would be authentication. There are many authorization methods in use out there and it would be impossible to account for every single case out of the box. However, with extensions, we keep the door open for new authentication mechanisms.</p><p>This is how extensions configuration looks:</p><pre># ...<br>extensions:<br>  health_check:<br>  pprof:<br>    endpoint: :1888<br>  zpages:<br>    endpoint: :55679<br> <br>service:<br>  extensions: [pprof, zpages, health_check]<br>  pipelines:<br>    # ...</pre><p>Technically, extensions are a special case of the collector’s components. They are plugged into predefined points of OTel workflows by implementing one or more interfaces:</p><ul><li>PipelineWatcher indicates if data can be ingested yet or not (useful for health checkers).</li><li>ConfigWatcher indicates changes in the OTel collector configuration.</li><li>StatusWatcher marks an extension as a component status listener.</li><li>auth.Server &amp; auth.Client signal that an extension can authenticate incoming client requests for receivers or outgoing requests for exporters correspondingly.</li></ul><figure><img alt="How extensions plug into OTel collector workflows" src="https://cdn-images-1.medium.com/max/1024/0*rZikYp59fqefvnkA.png" /><figcaption>How extensions plug into OTel collector workflows</figcaption></figure><p>Extensions may depend on other extensions, so the collector builds another DAG to get the startup/shutdown order of all of them.</p><blockquote><strong><em>Ensure Interfaces Are Implemented at Compilation</em></strong></blockquote><blockquote>OTel Collector heavily relies on components implementing various interfaces.</blockquote><blockquote>To make sure these components remain compatible with the interfaces over time, OTel uses this bizarre expression everywhere:</blockquote><blockquote><em>var _ Interface = (*Struct)(nil)</em></blockquote><blockquote>The expression says the interface must be implemented at all times. It gets the compiler involved and will trigger an error if there are any interface violations.</blockquote><blockquote>Without that, a standard interface check might silently stop detecting the components after modifications to their interfaces:</blockquote><blockquote><em>if ext, ok := component.(Interface); ok { // the component implements the interface}</em></blockquote><h4>Authentication</h4><p>OTel has two potential places where authentication is important:</p><ul><li>on the receiver’s side when it accepts new observability signals</li><li>on the exporter’s side, when it tries to offload collected signals for persisting</li></ul><p>Both cases are covered via extensions. The OTel Collector defines two separate extension interfaces to provide a token-based authentication.</p><p>Receivers implement authentication as a <a href="https://pkg.go.dev/net/http"><strong>net/http</strong></a> middleware. It passes an incoming HTTP request headers (or <a href="https://grpc.io/docs/guides/metadata/"><strong>gRPC metadata</strong></a>) to the authentication extension to do token validation. Another important middleware collects client information from the incoming request as an additional metadata or context (e.g. tenantID) for the following usage on the processing stage. HTTP receivers pull HTTP headers as metadata while gRPC receivers use the corresponding RPC metadata.</p><figure><img alt="OTel Collector Authentication" src="https://cdn-images-1.medium.com/max/1024/0*PK2EbVum7eFb_Fiy.png" /><figcaption>OTel Collector Authentication</figcaption></figure><p>Client authentication is based around overriding <a href="https://pkg.go.dev/net/http#RoundTripper"><strong>http.Client’s RoundTripper</strong></a> (RoundTrippers should not modify requests, so the collector has to copy the original request to pass authN data to the copy and send it further) or <a href="https://pkg.go.dev/google.golang.org/grpc/credentials#PerRPCCredentials"><strong>gRPC’s PerRPCCredentials</strong></a>.</p><p>As contrib extensions, the OTel Collector supports <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/basicauthextension"><strong>Basic</strong></a>, <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/bearertokenauthextension"><strong>Static Bearer Token</strong></a>, <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/oauth2clientauthextension"><strong>OAuth2 Client Credentials</strong></a>, <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/oidcauthextension"><strong>OIDC</strong></a>, and a few vendored authentications like <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/asapauthextension"><strong>ASAP</strong></a>.</p><p>The OTel Collector also supports mTLS authentication, but it’s done via the collector’s TLS configuration for servers and clients.</p><h4>ZPages</h4><p>ZPages is a way to peek into the internal state of the OTel Collector via a set of handly HTML. You can check out things like:</p><ul><li>trace data (e.g. /debug/tracez)</li><li>pipelines configuration (e.g. /debug/pipelinez)</li><li>feature gates (e.g. /debug/featurez)</li><li>Collector built-in service information (e.g. /debug/servicez)</li><li>extensions (e.g. /debug/extensionz)</li></ul><figure><img alt="ZPages Pipelines" src="https://cdn-images-1.medium.com/max/1024/0*EWuVMBONqOxqGy9Q.png" /><figcaption>ZPages Pipelines</figcaption></figure><figure><img alt="ZPages Feature Gates" src="https://cdn-images-1.medium.com/max/1024/0*Yy234cGx9fKFlzhU.png" /><figcaption>ZPages Feature Gates</figcaption></figure><p>ZPages works as an extension that expects the RegisterZPages() method to be implemented. The method is given with a <a href="https://pkg.go.dev/net/http#ServeMux"><strong>http.ServeMux</strong></a> and other components can register their pages. As an extension, Zpages offers a set of methods to render various simple UI primitives in a consistent style.</p><h3>Custom Collectors</h3><p>The OpenTelemetry Collector offers a lot of flexibility. You can extend it, install new receivers, processors, exporters, and extensions. But how exactly does that process work?</p><p>The collector is written in Golang and compiled into a single binary. This is great for performance, but not as easy to extend as a Python application, where you can install addons at runtime.</p><p>Indeed, to extend the OTel Collector, you need to build your own custom collector instance. However, OpenTelemetry tries to simplify that process with a separate CLI called the OTel Collector Builder (aka OCB).</p><p>OCB is a typical code generator. It takes a config that defines the Collector’s meta information and lists of receivers, processors, exporters, extensions as regular Go modules to install and plug in:</p><pre>dist:<br>  name: custom-collector<br>  description: Custom OpenTelemetry Collector<br>  output_path: ./dist<br> <br>exporters:<br>  - gomod: github.com/open-telemetry/opentelemetry-collector-contrib/exporter/alibabacloudlogserviceexporter v0.86.0<br>  - gomod: go.opentelemetry.io/collector/exporter/debugexporter v0.86.0<br> <br>receivers:<br>  - gomod: go.opentelemetry.io/collector/receiver/otlpreceiver v0.86.0<br> <br>processors:<br>  - gomod: go.opentelemetry.io/collector/processor/batchprocessor v0.86.0</pre><p>Using the config, it generates several files by rendering templates:</p><ul><li>go.mod file that includes all component modules to download and a set of the OTel collector core modules like go.opentelemetry.io/collector/otelcol.</li><li>components.go file that registers all component factories to inform the collector that they exist</li><li>main.go that tie together them all and calls the collector’s CLI</li><li>a few more files including tests that check an effective collector’s config structure after registering all components</li></ul><p>Finally, Builder compiles generated boilerplate by running go build with various flags and build tags via <a href="https://pkg.go.dev/os/exec"><strong>exec.Command()</strong></a>.</p><h3>Feature Gates</h3><p>The OpenTelemetry Collector has a feature gate system to guard functionality that is being developed from impacting real users.</p><p>Each feature gate may go through these stages:</p><ul><li>Alpha (a.k.a Private Preview) when the gate is disabled by default, but can be enabled on demand.</li><li>Beta (a.k.a. Public Preview) when the gate is enabled by default, but can be disabled on demand.</li><li>Stable (a.k.a. Generally Available or simply GA) when the gate is permanently enabled.</li><li>Deprecated when a feature was not fully proven to be useful and it’s on its way to be removed.</li></ul><p>Deprecated features stay there for two releases before being fully removed.</p><p>OTel has left an opportunity to deprecate or call back stable features, too. In that case, they move into the alpha stage for two releases and then get deprecated for two releases before being removed.</p><figure><img alt="Various evolution paths for OTel feature gates" src="https://cdn-images-1.medium.com/max/1024/0*katwDAjfoDj7qn0h.png" /><figcaption>Various evolution paths for OTel feature gates</figcaption></figure><p>Once the flag is deprecated and about to be removed, the removal itself is done manually via pull request.</p><p>In code, the feature gate functionality is represented as a feature gate registry where gates are registered on the global scope (and then checked somewhere in the codebase):</p><figure><img alt="The OTel Collector Feature Gates In Action" src="https://cdn-images-1.medium.com/max/1024/0*5kOERasfv2Vg6wsA.png" /><figcaption>The OTel Collector Feature Gates In Action</figcaption></figure><p>Users are in control of enabled gates by passing a special CLI flag.</p><h3>What’s next?</h3><p>We have already gone over <a href="https://www.romaglushko.com/blog/opentelemetry-sdk/"><strong>the design of OTel SDK</strong></a> and expored the internal of the collector in this article. But guess what? We still have not yet fully covered OpenTelemetry tooling.</p><p>One more topic that I would love to dive into in this series is the OpenTelemetry Kubernetes Operator and how it helps to deploy and scale the OTel Collector. But hey, let’s save that topic for another time.</p><p>If you’re enjoying this OpenTelemetry series, please share it on social media 🙌</p><h3>References</h3><ul><li><a href="https://github.com/open-telemetry/opentelemetry-collector"><strong>[Github] OTel Collector</strong></a></li><li><a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/"><strong>[Github] OTel Collector Contrib</strong></a></li><li><a href="https://github.com/open-telemetry/opentelemetry-go-build-tools"><strong>[Github] OpenTelemetry Go Build Tools</strong></a></li><li><a href="https://opentelemetry.io/docs/collector/"><strong>[OpenTelemetry] OTel Collector</strong></a></li><li><a href="https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/design.md"><strong>[OpenTelemetry] OpenTelemetry Collector Architecture</strong></a></li><li><a href="https://opentelemetry.io/docs/collector/custom-collector/"><strong>[OpenTelemetry] Buidling a custom collector</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cce94d40a7e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OTEL SDK: Concepts & Design]]></title>
            <link>https://roma-glushko.medium.com/opentelemetry-sdk-design-e378101b1612?source=rss-2607aea71af1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e378101b1612</guid>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[service-reliability]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Roma Glushko ]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 13:24:06 GMT</pubDate>
            <atom:updated>2024-07-30T13:24:06.107Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IgG_QRjTOjwZWX0B.jpg" /><figcaption>Photo By <a href="https://unsplash.com/photos/black-and-white-telescope-with-tripod-Utt2Kc2JyAc"><strong>Jennifer Lim-Tamkican</strong></a></figcaption></figure><p>OpenTelemetry is an observability framework and an active <a href="https://www.cncf.io/projects/opentelemetry/"><strong>CNCF project</strong></a> that provides a vendor-neutral and tool-agnostic way to collect observability signals across your heterogeneous system.</p><p>In this blog post series, we will dig into two big questions:</p><ul><li>how OpenTelemetry instrumentation works on the application side taking <a href="https://github.com/open-telemetry/opentelemetry-python/"><strong>Python’s SDK</strong></a> as an example. We will touch traces, metrics, logs and context propagation across services.</li><li>how OpenTelemetry Collector works under the hood and some of the interesting engineering decisions made there (see <a href="http://localhost:4321/blog/opentelemetry-sdk/"><strong>the OTEL Collector blog post</strong></a>)</li></ul><blockquote>The original article was posted on <a href="https://www.romaglushko.com/blog/opentelemetry-sdk/">my website</a>. Go and check it out!</blockquote><p>Gotta be fun 🙌</p><h3>The Problem</h3><p>With the rise of the open source community, people and organizations don’t really want to invest in proprietary protocols and standards anymore. Instead, it’s mainstream to pick a widely-recognized open source project as a basis to build on top of it.</p><p>In the observability domain, there are enough open source protocols that cover some of the three key pillars:</p><ul><li>Logs - stdout and stderr streams your services or application outputs while running in the container.</li><li>Metrics - aggregations of some measurements over a period of time</li><li>Traces - a visualization of the steps or the execution path that your workflow passed</li></ul><figure><img alt="The Three Pillars of Observability" src="https://cdn-images-1.medium.com/max/1024/0*AytT0u9No0lrSvmM.png" /><figcaption>The Three Pillars of Observability</figcaption></figure><p>When you think about metrics, <a href="https://prometheus.io/"><strong>Prometheus</strong></a> and <a href="https://github.com/statsd/statsd"><strong>statsd</strong></a> may come to your mind. On the traces side, there are <a href="https://www.jaegertracing.io/"><strong>Jaeger</strong></a> and <a href="https://zipkin.io/"><strong>Zipkin</strong></a>. There are also various beats that could scrap your logs like <a href="https://www.fluentd.org/"><strong>fluentd</strong></a> or <a href="https://grafana.com/oss/loki/"><strong>Grafana Loki</strong></a>.</p><p>Now if you want to cover all three pillars, you need to pick a combination of collectors/protocols to cover each one (well, some are capable of covering a few pillars). However, there are still a few problems left:</p><ul><li>even though the protocols are open source, they may still tightly connect your application to the underlying collector or storage, so it won’t be that easy to switch gears and use something else.</li><li>we have divided observability into three pieces, but in reality, they are three different signals or points of view on the application work, so we may get the whole picture and max value out of them when they are well connected and correlated for us.</li></ul><figure><img alt="The observability signals are unconnected when you use separate highly specialized protocols" src="https://cdn-images-1.medium.com/max/1024/0*AJpAbc5wWgfUXlbz.png" /><figcaption>The observability signals are unconnected when you use separate highly specialized protocols</figcaption></figure><p>To sum it up, we want to have:</p><ul><li>one open source vendor-lock-free protocol to rule all observability signals.</li><li>a stable abstraction for us for the underlying observability storage(s) without a need to migrate our service every time that storage changes.</li><li>a coverage of popular programming languages, not to be limited in what our tech stack looks like.</li></ul><figure><img alt="Observability signals with OTel" src="https://cdn-images-1.medium.com/max/1024/0*uwMBsWLoPMyp4rjj.png" /><figcaption>Observability signals with OTel</figcaption></figure><blockquote><strong><em>The OTEL Origin</em></strong></blockquote><blockquote>This ubiquitous open protocol idea is so compelling that at some point there were two projects, <a href="https://opentracing.io/"><strong>OpenTracing</strong></a> and <a href="https://opencensus.io/"><strong>OpenCensus</strong></a>, that were trying to fill the gap.</blockquote><blockquote>They were trying to compete with each other, but there was not the right context to do that, so it didn’t make sense to try to conquer some market shares, but rather to consolidate their effort and come there much quicker shaping the space.</blockquote><blockquote>That’s what happened. Both projects were merged into one known as <a href="https://opentelemetry.io/"><strong>OpenTelemetry</strong></a> (aka OTEL).</blockquote><h3>The SDK</h3><p>Collecting logs, metrics and traces in a unified way across services implemented in different technical stacks is the central task of OpenTelemetry. To get there, OpenTelemetry provides:</p><ul><li>SDKs for <a href="https://opentelemetry.io/docs/instrumentation/"><strong>11+ of the most popular languages</strong></a> (like Python, Go, NodeJS, Rust, Java, etc) that inits OTEL core components</li><li>library-specific instrumentations that provide tool/framework-specific signals and context automagically (e.g. <a href="https://www.starlette.io/"><strong>Starlette</strong></a>, <a href="https://www.python-httpx.org/"><strong>HTTPX</strong></a>, <a href="https://aio-pika.readthedocs.io/en/latest/"><strong>aiopika</strong></a> instrumentations, and so on)</li></ul><p>The third thing you could do is to further instrument your codebase with business logic specific traces and metrics.</p><p>This process is generally known as codebase <em>instrumentation</em>.</p><p>There are two ways to setup OTEL in your application:</p><ul><li>automatic — when you run some agent before the main application entry point that configures OpenTelemetry (but not all languages support it, for example, Golang doesn’t)</li><li>manual — when you configure OpenTelemetry yourself to start collecting your observability signals.</li></ul><p>To understand how OpenTelemetry SDK is designed and implemented, we will delve into the manual setup.</p><p>This is what it takes you to manually setup Python’s service:</p><pre>from opentelemetry import metrics, trace<br>from opentelemetry.sdk.metrics import MeterProvider<br>from opentelemetry.sdk.metrics.export import (<br>    ConsoleMetricExporter,<br>    PeriodicExportingMetricReader,<br>)<br>from opentelemetry.sdk.resources import SERVICE_NAME, SERVICE_VERSION, Resource<br>from opentelemetry.sdk.trace import TracerProvider<br>from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter<br> <br>span_processor = BatchSpanProcessor(ConsoleSpanExporter())<br>metric_reader = PeriodicExportingMetricReader(ConsoleMetricExporter())<br> <br>resource = Resource(<br>    attributes={<br>        SERVICE_NAME: &quot;notifications&quot;,<br>        SERVICE_VERSION: &quot;v42&quot;,<br>    }<br>)<br> <br>trace_provider = TracerProvider(resource=resource)<br>metrics_provider = MeterProvider(metric_readers=[metric_reader])<br> <br>trace_provider.add_span_processor(span_processor)<br> <br># Sets the global default providers<br>trace.set_tracer_provider(trace_provider)<br>metrics.set_meter_provider(metrics_provider)<br> <br># Creates a custom tracer from the global provider<br>tracer = trace.get_tracer(&quot;users&quot;)<br> <br># Creates a custom meter from the global provider<br>meter = metrics.get_meter(&quot;users&quot;)</pre><p>Let’s try to unpack what’s going on there.</p><h3>Resources</h3><p>First of all, let’s pay attention to the Resource. It is an abstraction around entities that could generate signals:</p><pre>from opentelemetry.sdk.resources import SERVICE_NAME, SERVICE_VERSION, Resource<br> <br>resource = Resource(<br>    attributes={<br>        SERVICE_NAME: &quot;notifications&quot;,<br>        SERVICE_VERSION: &quot;v42&quot;,<br>    }<br>)</pre><p>Right off the bat, Resource illustrates a few important concepts in the observability domain.</p><p>Most context in the observability signals are going to be conveyed via attributes or tags which are essentially key-value pairs. Then, the observability backend could do some processing of these values to correlate various pieces of information.</p><p>OTEL strives to standardize the attribute names to keep them consistent across your system. That’s why they come as constants. In practice, this is an extremely daunting and challenging task, especially when multiple teams are working on different services in parallel.</p><h3>Providers</h3><p>Python’s SDK comes with two modules called trace and metrics. Both modules contain a global variable that holds the current provider and a setter method like set_tracer_provider() to configure it.</p><p>If you don’t want to configure a real provider, there are also NoOpTracerProvider or NoOpMeterProvider that are helpful to keep all custom instrumentations in place without a need for guarding them via ifs, for example.</p><blockquote><strong><em>Design Patterns in Wild</em></strong></blockquote><blockquote>All providers have NoOp implementations which is a great example of <a href="https://refactoring.guru/introduce-null-object"><strong>the null object pattern</strong></a>. Since telemetry could spread across codebase, it would be disastrous to have if statements everywhere we had it in case we have no proper observability setup under some circumstances like during automated testing.</blockquote><p>Then, the rest of the codebase refers to the global providers when it needs to create traces or metrics.</p><figure><img alt="The Tracer &amp; Meter Registries" src="https://cdn-images-1.medium.com/max/1024/0*3tzAxWVjJaWUs3rO.png" /><figcaption>The Tracer &amp; Meter Registries</figcaption></figure><h3>Traces</h3><p>The TracerProvider is basically a factory that creates Tracers and passes most of its params down to a Tracer. Tracers represent the specific trace that could contain many spans.</p><p>Conceptually, traces are connected to the specific workflow or operation in the system. That’s why their names should be the same for the same processes e.g. GET /users/{user_id}/ may represent all requests to an API that returns user’s data.</p><p>Then, spans may represent some steps in your workflow. For instance, to get the user information, you may need to perform a request to your database. That action may be wrapped into a span. Additional attributes could be added to the span to record some events, action result statuses, etc. In the end, all spans form a hierarchical tree that could be viewed in the observability backend.</p><figure><img alt="An example of trace" src="https://cdn-images-1.medium.com/max/1024/0*Iz27x0FUO2JjNwpw.png" /><figcaption>An example of trace</figcaption></figure><p>Using <a href="https://www.romaglushko.com/blog/opentelemetry-sdk/#the-sdk"><strong>the tracer inited above</strong></a>, we can create a new trace via:</p><pre># the root span <br>with tracer.start_as_current_span(&quot;users:get-info&quot;) as span:<br>    span.set_attribute(&quot;user_id&quot;, str(...))<br> <br>    # nested/child span<br>    with tracer.start_as_current_span(&quot;users:get-info:check-permissions&quot;) as span:<br>        ...</pre><h3>Spans</h3><p>In OTEL protocol, traces are rather virtual entities that hold some execution context. The real data points that are being collected, processed and exported are spans.</p><p>The Span consists of:</p><ul><li>name — the human-friendly title of the step</li><li>kind like internal, server, client, producer, consumer</li><li>status like not set, ok, error</li><li>the span context</li><li>the parent span context</li><li>the resource context</li><li>the trace or instrumentation scope</li><li>span attributes</li><li>span events — special entities with the name, timestamp and own set of attributes</li><li>span links to other spans that have caused the current span</li><li>start_time &amp; end_time as time.time_ns()</li></ul><p>The Span class is also a <a href="https://book.pythontips.com/en/latest/context_managers.html#context-managers"><strong>context manager</strong></a>, so when it starts and exits, the span signals the SpanProcessor about that.</p><h3>Span Sampling</h3><p>There is also an optional opportunity to configure a span sampler.</p><p>Sampling is a way to filter out some spans or other data points if they match some specific criteria or just randomly. The major reasons to sample are:</p><ul><li>to optimize the cost of ingesting and storing observability signals</li><li>filter out boring regular data and mostly keep interesting one e.g. spans with errors, that took more than the threshold</li><li>merely filter based on the presence or absence of attributes</li></ul><p>Sampling on the SDK side could allow filtering as soon as possible in the pipeline (or the head sampling).</p><p>OTEL comes with a few span samplers out of the box:</p><ul><li>StaticSampler that always or never drops spans</li><li>TraceIdRatio that probabilistically drops a given portion of spans</li></ul><figure><img alt="OTel SDK Span Pipeline" src="https://cdn-images-1.medium.com/max/1024/0*mqBUVe8ZfMtsFnuy.png" /><figcaption>OTel SDK Span Pipeline</figcaption></figure><p>These two samplers could be also configured to respect parent span decisions, so if the parent span was dropped, all its children spans would be eliminated, too.</p><p>They were trying to compete with each other, but there was not the right context to do that, so it didn’t make sense to try to conquer some market shares, but rather to consolidate their effort and come there much quicker shaping the space.</p><p>That’s what happened. Both projects were merged into one known as <a href="https://opentelemetry.io/"><strong>OpenTelemetry</strong></a> (aka OTEL).</p><blockquote><strong><em>Design Patterns in Wild</em></strong></blockquote><blockquote>Parent span aware sampling is implemented using <a href="https://refactoring.guru/design-patterns/composite"><strong>the composite design pattern</strong></a>.</blockquote><blockquote>The parent-based sampler wraps the static or ration-based sampler mentioned above and adds a logic to propagate the parent span’s sampling decision.</blockquote><h3>Span Processors</h3><p>When spans end, they come to span processors. Span processing is the last stage of span’s lifecycle before it’s exported outside of the service. OpenTelemetry uses it to batch spans and multiplex them to multiple exporters.</p><p>The BatchSpanProcessor collects spans and exports them on schedule or when its queue is full. For that, it maintains a separate daemon thread where this logic is executed. The processor waits until a batch is collected or a timeout is reached. <a href="https://docs.python.org/3/library/threading.html#condition-objects"><strong>Threading.condition</strong></a> is used to implement this elegantly.</p><figure><img alt="A Batch Queue with Timeout" src="https://cdn-images-1.medium.com/max/1024/0*0j0XjpBJ7Bk1swn2.png" /><figcaption>A Batch Queue with Timeout</figcaption></figure><p>There are also two MultiSpanProcessors that operate on a list of span processors and dispatch them sequentially or concurrently.</p><p>The concurrent span processing happens via <a href="https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor"><strong>ThreadPoolExecutor</strong></a>.</p><h3>Ctx Propagation</h3><p>So far we have been talking about trace spans processing in the scope of one services, but the real value of traces unlocks when multiple microservices take part in a workflow and you could connect what they were doing there into one coherent picture.</p><p>In order to do that, OpenTelemetry needs to propagate some context during cross-service communication, so the next microservice in the flow would know that all spans it was going to create should be attached to the parent trace created at the start of the workflow.</p><figure><img alt="The Context Propagation in a Distributed Workflow" src="https://cdn-images-1.medium.com/max/1024/0*BWcybnFJg8TppjIm.png" /><figcaption>The Context Propagation in a Distributed Workflow</figcaption></figure><p>OTEL holds propagatable information in the runtime context. In Python’s SDK, it’s implemented using the convenient <a href="https://docs.python.org/3/library/contextvars.html"><strong>contextvars</strong></a> standard library which is a perfect mechanism to have scoped “global” variables on the level of asyncio.Task-s, for example.</p><p>By default, OTEL defines two context vars:</p><ul><li>the current span — holds a reference to the currently active OTEL trace span</li><li>the baggage — holds arbitrary key-value information that should be propagated as an additional context for every microservice involved</li></ul><p>Another important thing here is the actual context propagation which incurs context serialization and deserialization.</p><p>In the realm of HTTP-based communication, OpenTelemetry propagates the context via HTTP headers according to <a href="https://www.w3.org/TR/trace-context/"><strong>the W3C Trace Context specification</strong></a>. According to the specification, the current span context is propagated as two headers:</p><ul><li>traceparent - with trace span ID, parent span ID and parent span flags (e.g. trace was marked as sampled or not)</li><li>tracestate - arbitrary vendor-specific trace context or identifiers</li></ul><p>The baggage context doesn’t seem to be outlined in the specification, but OTEL shares it as one more identically named HTTP header.</p><p>The microservice that receives such requests should be aware of context information in the headers, extract it and set it in the local runtime context.</p><p>Since OpenTelemetry is framework- or transport-protocol-agnostic, it just provides all needed functions to extract or inject context. To actually propagate that information, you should instrument your clients and servers and OTEL provides plenty of auto-instrumentors in <a href="https://opentelemetry.io/ecosystem/registry/"><strong>their registry</strong></a>.</p><h3>Metrics</h3><p>Metrics are another observability pillar we are going to review next. The mechanism of collecting metrics is a bit different to traces.</p><p>In case of traces, user code actively creates trace spans and as soon as they are completed, OpenTelemetry can process and export them. The metrics dynamic is much more continuous, so the collection really ends when the service shuts down. Since service uptime could be measured in days if not weeks, we need to take a different approach here to export all measurements in between like doing metric data aggregations periodically over a time window.</p><p>Just like in the case of traces, OpenTelemetry provides MeterProvider that bridges all metrics with metric exporters. MeterProvider creates new instances of Meter. Meters are instrumentation-specific measurement components. Each OTEL instrumentation library creates its own meter (e.g. HTTP client or server meters). When you do your custom measurements it’s alright to have one global meter per service (but you certainly could have more).</p><p>Using <a href="https://www.romaglushko.com/blog/opentelemetry-sdk/#the-sdk"><strong>the meter inited above</strong></a>, you can measure a custom metric like that:</p><pre># globally defined custom metric<br>user_info_cache_miss_counter = meter.create_counter(<br>    &quot;users.cache.miss&quot;,<br>    description=&quot;The number of cache misses when fetching user&#39;s info&quot;,<br>)<br> <br># later on, you can import the metric and measure what you need<br>user_info_cache_miss_counter.add(1, {&quot;user.org_id&quot;: ...})</pre><h3>Metric Instruments</h3><p>Now, having a meter, you could create specific metrics (a.k.a. metric instruments) that you want to measure or observe. Generally, OTEL divides metrics into two categories:</p><ul><li>Synchronous metrics - there are metrics that you measure directly right in your service workflows, so you observe them as soon as the event happens (e.g. a service increases a counter metric in the user login workflow)</li><li>Asynchronous (or observable) metrics - these metrics are read from “external” sources, so you just observe an aggregated or in-time statistics instead of measuring the value directly (e.g. number of items in a queue given that you cannot instrument the queue directly and you could just read its size property)</li></ul><p>OpenTelemetry supports the following metric types:</p><ul><li>Counter (and Observable Counter) — an ever-growing (or monotonically increasing) value (for example, the number of requests processed by service)</li><li>UpDownCounter (and Observable UpDownCounter) — a value that could grow or fall (for example, the number of in-flight requests)</li><li>Histogram (and Observable Histogram) — suitable for measurements on which you want to calculate statistics (for example, request latency)</li><li>Gauge — just like the observable UpDownCounter, but each measurement is treated as a separate data point, so they are not summed up (for example, CPU or RAM utilizations)</li></ul><h3>Views &amp; Aggregations</h3><p>With our metrics defined, we could start measuring, aggregating and collecting actual values.</p><p>Metric instruments don’t collect data directly but rather send it to MeasurementConsumer which is a global component initiated on the MeterProvider’s level. MeasurementConsumer collects data for each and all MetricReaders configured on the provider.</p><figure><img alt="The Architecture of OTel Metrics" src="https://cdn-images-1.medium.com/max/1024/0*YaK4qdDFpKmyhnCf.png" /><figcaption>The Architecture of OTel Metrics</figcaption></figure><p>Thinking about our source metrics data, it’s just arrays of numbers with attributes (or one number at the time in the case of observable instruments), so there are multiple options possible how they could be aggregated. OpenTelemetry provides great flexibility there.</p><figure><img alt="OTel Metrics, Views, Aggregations" src="https://cdn-images-1.medium.com/max/1024/0*DAg-LKZ8Xu3EHal9.png" /><figcaption>OTel Metrics, Views, Aggregations</figcaption></figure><p>First of all, aggregations could be configured on the metric exporter side. Maybe, you are an observability backend vendor like DataDog or Chronosphere and you come up with a better or specific way to deal with metric data points. This would be an opportunity for you to adjust exported data.</p><p>Then, you could leverage a concept of views to override the config further. Views effectively allow to specify the aggregation strategy per metric instrument and its metadata (e.g. name, attributes).</p><p>By default, OTEL implements the following aggregations:</p><ul><li>Drop Aggregation — a way to drop metric collection completely.</li><li>Last Value Aggregation — keeps the last aggregated value until it’s collected (used by gauges).</li><li>Sum Aggregation — arithmetic sum of provided data points (used by counters).</li><li>Explicit Bucket Histogram Aggregation — assigns collected data points to one of 15 predefined buckets. Besides that, it collects sum, count, min and max across given data.</li><li>Exponential Bucket Histogram Aggregation — similar to the explicit bucket aggregation, but buckets are generated dynamically by the exponentially growing size of the next bucket and much more fine grained (by default, there are 150 buckets).</li></ul><p>The sum and histogram aggregations may collect data between probes as:</p><ul><li>deltas e.g. differences between the previous aggregated stats (e.g. sums, counts) and the current ones.</li><li>cumulative data e.g. the previous and the current stats are summed up (so the values keep increasing over time).</li></ul><p>This is called aggregation temporality.</p><figure><img alt="Aggregation Temporalities" src="https://cdn-images-1.medium.com/max/1024/0*ogki-QWrtuR00tkN.png" /><figcaption>Aggregation Temporalities</figcaption></figure><h3>Metric Readers</h3><p>As we briefly have mentioned, metrics are collected on schedule by MetricReader like PeriodicExportingMetricReader which holds a ticker in a separate thread. The ticker initiates the metrics collection process that creates exportable data according to metrics aggregation temporalities.</p><h3>Logs</h3><p>Finally, we get to logs. They are the most wide-spread among the signals and have the longest record of being used for diagnosing how code works.</p><p>Logs are simple to operate. You could just write them to a standard output or a file, and then dredge them when you need. No need to have special viewers like you would need in case of traces or metrics. That’s why pretty much all languages have their off-the-shelf logging libraries to use.</p><p>Ironically, logs have gotten the last into OpenTelemetry. The integration is either in the experimental stage or doesn’t exist for most languages at the moment.</p><figure><img alt="The Log Bridge in Python" src="https://cdn-images-1.medium.com/max/1024/0*NDp0eBA2DW-bDhYB.png" /><figcaption>The Log Bridge in Python</figcaption></figure><p>OpenTelemetry bridges into the existing logging libraries to integrate logs seamlessly for applications. In Python’s world, there is the standard <a href="https://docs.python.org/3/library/logging.html"><strong>logging</strong></a> package. OTEL comes with a LoggingHandler that plugs the rest of components into the logging system. The LoggingHandler also translates logging.LogRecord into OTEL’s LogRecord data class.</p><blockquote><strong><em>Design Patterns in Wild</em></strong></blockquote><blockquote>The OTEL’s LoggingHandler is a good example of applying <a href="https://refactoring.guru/design-patterns/adapter"><strong>the adapter pattern</strong></a> that allowed OpenTelemetry to have its own architecture despite a variety of logging libraries it needed to support.</blockquote><p>The remaining architecture resembles what we have reviewed in <a href="https://www.romaglushko.com/blog/opentelemetry-sdk/#span-processors"><strong>the trace part</strong></a>. There is a dedicated LoggerProvider that holds log processors and exporters attached to the processors. The processors send logs to exporters for further saving in observability backends.</p><h3>SemConv</h3><p>Before wrapping up, we need to touch on another important topic that is tangentially connected to service instrumentations and metrics.</p><p>Imagine you have three teams in a company that run different subsystems. Now let’s ask them to define golden signal metrics for their services and see what metric names they come up with. Chances are we would get three different sets of names for semantically the same metrics. That’s even more likely if they work with different tech stacks with different conventions and naming standards.</p><p>Such a lack of consistency would create a lot of mess and hinder reuse of common dashboards, alerts, etc. The same situations can happen in traces when we instrument database queries, object storage access, etc.</p><p>OTEL recognized this problem and <a href="https://opentelemetry.io/docs/specs/semconv/"><strong>came up with a set of common names for common operations across all three signals</strong></a>. So if you use it, you can come up with a very unified view of the whole system when looking at it through an observability lens.</p><h3>Conclusion</h3><p>In this article, we have reviewed OpenTelemetry integration from the service development perspective by looking into the internals of the SDK.</p><p><a href="https://www.romaglushko.com/blog/opentelemetry-collector/">In the next part</a>, we will see what happens with logs when they come to the OTEL Collector.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e378101b1612" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built my ML workstation ]]></title>
            <link>https://medium.com/data-science/how-i-built-my-ml-workstation-f799c1de0341?source=rss-2607aea71af1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f799c1de0341</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hardware]]></category>
            <dc:creator><![CDATA[Roma Glushko ]]></dc:creator>
            <pubDate>Thu, 10 Jun 2021 13:03:30 GMT</pubDate>
            <atom:updated>2021-06-10T13:03:30.115Z</atom:updated>
            <content:encoded><![CDATA[<h4>A full story about building a custom ML workstation. From parts picking to software installation and using.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-BL4LpXx0yUyPcajKMVXVg.jpeg" /><figcaption>Me trying to unpack workstation parts</figcaption></figure><p>Kaggle Kernels and Google Colab are great.</p><p>I would drop my mic at this point if this article was not about building a custom ML workstation.</p><p>There are always some “buts” that make our lives harder. When you start to approach nearly real-life problems and you see hundreds of gigabytes of large datasets, your gut feeling starts to tell you that your CPU or AMD GPU devices are not going to be enough to do meaningful things. This is how I came here.</p><p>I was taking part in <a href="https://www.kaggle.com/c/hpa-single-cell-image-classification">Human Protein Atlas (HPA) — Single Cell Classification</a> competition on Kaggle. HPA dataset contains nearly 150Gb of 8bits 4-channels protein images. 16bits variant of the dataset holds 350Gb.</p><p>Here is what I had at my disposal:</p><ul><li>MacBook Pro 2019 (Intel Core i9 &amp;&amp; Intel UHD Graphics 630 1536MB &amp;&amp; 16GB DDR4)</li><li>~30h GPU and/or ~30h TPU hours per week on Kaggle Kernels</li></ul><p>Sounded good. I thought I would be able to prototype locally and then execute notebooks on the cloud GPU. What could go wrong?</p><h3>Life Without GPU</h3><p>As it turned out, there are a lot of frictions in the mentioned workflow.</p><p>First of all, my solution source code quickly became an entire project with a lot of source code and dependencies. I used <a href="https://python-poetry.org/">poetry</a> as a package manager and decided to generate an installable package every time I made meaningful changes to the project in order to test them in the cloud. These installable packages I was uploading into a private Kaggle dataset which in turn was mounted to a notebook. The notebook was calling classes and functions from the package.</p><p>This approach turns out to have underwater stones. Kaggle notebooks randomly thrown weird errors after installing project packages. I think it was related to dependency version mismatch and I spotted errors like “method X is not found in package Y”, etc. Autoreload was not helpful. Several mornings in a row I started my day dealing with new and new suddenly occurred unearthly issues.</p><p>While working on the competition, I switched from Keras to PyTorch. PyTorch is much slower on CPU than TensorFlow or Keras. It was time-consuming to even perform a dev run of my recent changes. However, PyTorch has outstanding support in academic and other ML-associated communities which means a bunch of (<strong>almost</strong>) read-to-use examples of state-of-art technics.</p><p>Also, when you run your code in the cloud, you can not easily experiment. You have to plan what you are going to experiment with and make those places somehow configurable beforehand.</p><p>All in all, the experience was frustrating. I clearly realized if I wanted to do more complex deep learning experiments and projects, then I just need to have 24/7 access to any kind of GPUs.</p><h3>Investigation</h3><p>I have never been interested in custom PC building, hardware or gaming. So it took me a while to understand what did it cost me to build a custom machine.</p><p>There are a lot of resources on building gaming PCs. While building a deep learning workstation sounds like a similar task, there are nuances that should be accounted in order to build a cost-efficient and ML-compatible machine.</p><p>I have found a few useful blog posts which helped me quickly to grasp the topic. Particularly, I could highlight two posts from <a href="https://twitter.com/Tim_Dettmers">Tim Dettmers</a>:</p><ul><li><a href="https://timdettmers.com/2018/12/16/deep-learning-hardware-guide/">A Full Hardware Guide to Deep Learning</a></li><li><a href="https://timdettmers.com/2020/09/07/which-gpu-for-deep-learning/">Which GPU(s) to Get for Deep Learning: My Experience and Advice for Using GPUs in Deep Learning</a></li></ul><p>In his blog, Tim explained at length the importance of each PC part for ML workstation and provides general pieces of advice on choosing them. Here I’m going to mention information that was helpful for me along with details Tim did not focus on.</p><p>Also, <a href="https://pcpartpicker.com/">PCPartsPicker’s Builder</a> was super helpful during planning PC. It suggests possible components compatibilities and things to check before ordering the list. It helped to overcome my constant fear that I could buy something that would not work together.</p><h3>Parts for ML build</h3><p>When it comes to building a deep learning machine (or any custom PC), there are 8 parts that should be considered:</p><ul><li><a href="https://www.romaglushko.com/blog/how-i-built-my-ml-workstation/#gpu">GPU</a></li><li><a href="https://www.romaglushko.com/blog/how-i-built-my-ml-workstation/#motherboard">Motherboard (a.k.a. MoBo)</a></li><li><a href="https://www.romaglushko.com/blog/how-i-built-my-ml-workstation/#cpu">CPU</a></li><li><a href="https://www.romaglushko.com/blog/how-i-built-my-ml-workstation/#ram">RAM</a></li><li><a href="https://www.romaglushko.com/blog/how-i-built-my-ml-workstation/#storage">Storage</a></li><li><a href="https://www.romaglushko.com/blog/how-i-built-my-ml-workstation/#power-system-unit">Power System Unit (PSU)</a></li><li><a href="https://www.romaglushko.com/blog/how-i-built-my-ml-workstation/#cooling">Cooling</a></li><li><a href="https://www.romaglushko.com/blog/how-i-built-my-ml-workstation/#pc-case">PC case</a></li></ul><p>Here is an overview:</p><h3>GPU</h3><p>GPU is <strong>the key component</strong> of any ML workstation. It’s designed to perform computations on <strong>big chunks of data</strong> (throughput-optimized) <strong>in parallel</strong> which makes it perfect for model training or inference where it’s really needed (<a href="https://www.quora.com/Why-are-GPUs-well-suited-to-deep-learning/answer/Tim-Dettmers-1">details are here</a>).</p><p>The very first consideration is that we need <strong>NVIDIA graphic cards only</strong> for deep learning. Unfortunately, there is a monopoly in the ML framework world. Most of the popular and production-ready frameworks (TensorFlow, PyTorch, Keras) are designed and optimized for CUDA-enabled devices. CUDA is a proprietary platform and set of APIs for parallel computations owned by NVIDIA. This is the reason why we mean “CUDA cards” when talking about the GPU in the ML context.</p><p>It makes sense to dig just slightly deeper in a simplified CUDA architecture. Modern GPUs are based on <strong>tensor cores</strong> that are capable of multiplying <strong>4x4 matrices in one operation</strong> which is blazing fast. Despite that, tensor cores need data to perform computations on. Data passes the following way in order to be loaded efficiently:</p><ul><li><strong>From RAM to Global GPU Memory</strong>. CPU threads load preprocessed batches into entirely separate GPU device memory (don’t be confused with PC RAM). The device memory is the slowest kind of memory in the GPU.</li><li><strong>From Global GPU Memory to Shared Memory</strong>. Shared memory is <strong>~10–50x faster</strong> than the global GPU memory, but it’s also much smaller (normally hundreds of Kbs). This memory is purely available for a Streaming Multiprocessor (SM) that is an analogue of CPU core in GPU architecture. Data is stored there in so-called tiles.</li><li><strong>From Shared Memory to Tensor Core Registries</strong>. Streaming Multiprocessors operates their tensor cores in parallel and upload part of the tiles into tensor core registries.</li></ul><p>So any bottlenecks in data loading flow would lead to suboptimal utilization of tensor cores, no matter how many of them you have in your GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*MeAeSQEu0sN1ovXWX9cFCw.png" /><figcaption>CUDA Hardware Architecture (<a href="https://dadaiscrazy.github.io/usuba/2020/03/28/CUDA-basics.html">source</a>, attached with permissions of image author)</figcaption></figure><p>With that being said, these are roughly the main GPU features important for ML tasks:</p><ul><li><strong>Global GPU Memory</strong> — defines how big batch sizes you can use during training or how quality samples you can use if it comes to computer vision</li><li><strong>Memory Bandwidth</strong> — a rate at which data is being transferred inside of the device</li><li><strong>Architecture</strong> — the more recent architecture is the better. Newer architectures may be better in terms of shared memory size, feature set (like mixed precision computations) and could be more efficient in terms of wattage per effective computations metric.</li></ul><p>Additionally, you should think about these factors:</p><ul><li><strong>Performance per Cost</strong></li><li><strong>GPU Cooling</strong></li><li><strong>GPU Wattage</strong></li></ul><p>Thankfully, you can find much more on that in the <a href="https://timdettmers.com/2020/09/07/which-gpu-for-deep-learning/">Tim’s post</a>.</p><h3>Motherboard</h3><p>The motherboard integrates most of the components and also provides:</p><ul><li>most of the I/O ports (like USB, Ethernet, etc)</li><li>chipset with BIOS</li><li>WiFi, Bluetooth adapters</li></ul><p>The motherboard provides other interfaces to power your stuff. Among them, the one of most important is CPU socket. Motherboards are divided into AMD- and Intel-compatible sockets which are not interchangable. Hence, you need to make sure <strong>the CPU of you choice</strong> is <strong>compatible with your motherboard</strong>.</p><p><strong>The number of PCI ports</strong> is another thing to consider. Since PCI ports are used to connect GPUs, you need to plan ahead your build and rooms for upgrades (to be able to add more cards in the future, for example). Also, pay attention that, effectively, graphic cards take more than one slot of space. We want to have <strong>as much space as possible</strong> between cards for <strong>better air cooling</strong>.</p><p>Also, I’m pretty sure you would be happy to have build-in WiFi adapter. Otherwise, the only way to connect a PC would be via ethernet cable which is not always convenient (or just buy an external adapter).</p><h3>CPU</h3><p>CPU is the “right hand” of GPU. In ML builds, CPU is used for:</p><ul><li><strong>Preprocessing Dataset</strong></li><li><strong>Loading batches into RAM</strong></li><li><strong>Transmitting batches from RAM to the GPU global memory</strong></li><li><strong>Running functions in GPU device</strong></li></ul><p>So it’s not really helpful to have high CPU frequency. Nonetheless, it’s important to be able effectively to execute small tasks in parallel. In other words, the number of <strong>threads and cores</strong> are important property for ML machines.</p><h3>RAM</h3><p>When it comes to RAM, the <strong>memory capacity</strong> is all that matters. It’s perfect to have enough RAM to run model training without falling back to <strong>swapping</strong>. Larger capacity would allow to run bigger batches of data and execute more data loaders to make GPU wait less.</p><p>RAM is also helpful during <strong>data processing and feature engineering</strong>. Hence, the larger RAM you would have, the better would be for you.</p><h3>Storage</h3><p>In deep learning, storage is used for <strong>persisting datasets</strong>. Since nowadays datasets are measured in gigabytes, it’s good to have at least <strong>a few terabytes</strong> of free disk space. Generally, people install the SSD for OS needs and datasets which is currently in use. The HDD is still helpful, because it’s cheaper than the SSD and it’s easier to afford terabytes of space for storing other datasets.</p><p>Among SSDs, you could find <a href="https://www.microcontrollertips.com/why-nvme-ssds-are-faster-than-sata-ssds/">NVMe SSDs</a> on the market which use a faster connection protocol. Prefer this kind of SSD if you can afford them.</p><h3>Power System Unit</h3><p>The PSU is what makes your PC alive. To choose your PSU, you need to calculate the <strong>wattage consumption</strong> of your build. Typically there are two the most power consuming components: <strong>CPU and GPUs</strong>. If you sum up their consumptions and adds another 10–15% on top of that (for other components, overclocking, etc), you would roughly estimate your power needs. I also used <a href="https://pcpartpicker.com/">PCPartpicker Builder</a> to estimate my PC wattage.</p><p>Other than that, you should consider the number of <strong>slots and connectors</strong> that the PSU provides.</p><p>This is the point where you can plan ahead. Just include potential GPUs you would like to buy in the future to the wattage consumption and connectors consideration.</p><h3>Cooling</h3><p>With a great power comes a great responsibility need for cooling.</p><p>Normally, you would need <strong>an air cooling</strong>. Making sure there is <strong>enough space between GPUs</strong> is a great no-overhead way to cool your system. It’s particularly good in 1–2 GPUs setup. <strong>A water cooling</strong> is a good option for 3+ GPUs setups.</p><p>CPU could get hot very quickly. So they usually are sold with basic coolers. This should be enough if you manage to avoid lots of air bubbles during the thermal gel installation. If you want to replace a stock cooler with a better one, make sure that a new cooler supports your CPU socket.</p><h3>PC Case</h3><p>The computer case protects all components from the outside environment. Also, it may provide:</p><ul><li><strong>Additional system coolers</strong></li><li><strong>Additional I/O ports</strong> (USB, Type-C, etc)</li><li><strong>Cable management</strong></li><li><strong>Vertical slots for GPUs</strong></li><li><strong>Slots for SATA disks</strong></li><li><strong>Cool design and look</strong> (well, that may matter)</li></ul><p>One of the most important considerations is the <strong>ability to hold</strong> all your cooling systems and GPUs. If your case is too small, it may be problematic.</p><h3>My Parts List</h3><p>Creating a multi-GPU cluster was not on my list. Yet still I wanted to have room for improvements. So I took <a href="https://pcpartpicker.com/user/tim_dettmers/saved/#view=mZ2rD3">2-GPUs barebone from Tim’s templates</a> as a base for my workstation and adjusted it a bit to match what I could find on the local market. Here is my final list of components:</p><ul><li>GPU: <a href="https://www.newegg.com/gigabyte-geforce-rtx-3070-gv-n3070aorus-m-8gd/p/N82E16814932359">Gigabyte GeForce RTX 3070 8Gb Aorus Master</a></li><li>Matherboard: <a href="https://www.newegg.com/msi-performance-gaming-x470-gaming-plus-max/p/N82E16813144266">MSI x470 Gaming Plus</a></li><li>CPU: <a href="https://www.newegg.com/amd-ryzen-5-3600/p/N82E16819113569">AMD Ryzen 5 3600</a></li><li>RAM: <a href="https://www.newegg.com/g-skill-32gb-288-pin-ddr4-sdram/p/N82E16820232091">G.Skill Ripjaws V Series 32Gb (2 x 16Gb)</a></li><li>Storage: <a href="https://www.newegg.com/samsung-970-evo-plus-500gb/p/N82E16820147742">Samsung 970 Evo 500Gb M.2–2280 NVME</a></li><li>Cooling: <a href="https://www.newegg.com/cooler-master-hyper-212-black-edition-rr-212s-20pk-r1/p/N82E16835103278">Cooler Master Hyper 212 Black Edition</a></li><li>PSU: <a href="https://pcpartpicker.com/product/MfJwrH/evga-power-supply-220g20750xr">EVGA G2 750W 80+ Gold</a></li><li>PC Case: <a href="https://www.newegg.com/matte-black-nzxt-h-series-h510-atx-mid-tower/p/N82E16811146315">NZXT H510</a></li><li>Wireless Adapter: <a href="https://www.newegg.com/tp-link-archer-t2u-plus-usb-2-0/p/N82E16833704471">TP-Link Archer T2U Plus</a></li></ul><p>The same list can be found on <a href="https://pcpartpicker.com/user/roman-glushko/saved/8gZHGX">PCPartsPicker</a>.</p><p>A few notes about the differences of my list compared to the original barebone. I have replaced a PSU and a cooler from the barebone following advice from Reddit users that said that changed parts are more up-to-date and modern.</p><p>Also, I was able to buy only 750W version of EVGA G2. My estimated wattage is 420W, so 650W version should have been enough. Nevertheless, more capable PSU gives more flexibility in terms of further part updates.</p><p>The situation with GPU was much more complicated. It was the beginning of the GPU shortage (end of 2020 — beginning of 2021) when GPU prices skyrocketed twice or sometimes three times. In that time, Bitcoin jumped to almost $60k as well as other factors that impacted the supply chain and increased GPU demand (mostly, global COVID-19 lockdown).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKD-kVTh7NvyCvu30HKTGg.png" /><figcaption>GPU Price Dynamics: end of 2020 — beginning of 2021. Wild time (<em>Image by author</em>)</figcaption></figure><p>I had been closely watching for price updates for like 3 months. The situation was not really changing. Well, it got even worse while I was waiting.</p><p>Considering Tim’s advice and crazy GPU prices, I was shooting for RTX 3070. RTX 2080 Ti would be also a great fit, but the market ran out of them pretty quickly.</p><p>There turned out to be a lot of vendors that produce RTX 3070 cards.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FN3lfXsa08CY&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DN3lfXsa08CY&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FN3lfXsa08CY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bf0153249052bb4fb6093941bff30d9/href">https://medium.com/media/9bf0153249052bb4fb6093941bff30d9/href</a></iframe><p>Basically, the main differences are in:</p><ul><li><strong>Max Power Limit</strong> — affects GPU performance.</li><li><strong>Quality of the card cooling system</strong> — the ability to cold card and sustain performance for a long time.</li><li><strong>Fan Noise</strong> — it’s just annoying to run noisy cards (particularly if you working in a place where other people work or live).</li></ul><h3>Hardware Installation</h3><p>It took me a couple of weeks to collect all parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YiuxSsdA2CAMbNw_vjz4sA.jpeg" /><figcaption>PC parts arrived. I think I could build a new house with these boxes. Stay tuned for more updates on this (<em>Image by author</em>)</figcaption></figure><p>Before unboxing all of those packages, keep in mind the following:</p><ul><li>You need to <strong>discharge static electricity</strong> that may be on your hands. Static electricity can damage your components particularly your motherboard. Fortunately, it’s easy to do. You need to periodically touch any metal object like your PC case, heater or filing cabinet. If you feel paranoid, there are <a href="https://www.newegg.com/rosewill-rtk-001/p/N82E16899261001">special wrist straps</a> for you.</li><li>Be careful when you install or connect your components. Parts and cables are designed to be connected easily. If you find yourself <strong>pressing too much</strong>, chances are it’s a signal to revisit what you are trying to connect and how. Exceptions happen since you probably would buy new things which have never been connected.</li></ul><p>Now it’s time to get our hands dirty!</p><h3>Motherboard</h3><p>The motherboard is a central component. So I started unboxing from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fLZDhEvjM8b38G-kqfcbQ.jpeg" /><figcaption>Motherboard Unboxing (<em>Image by author</em>)</figcaption></figure><p>It has lots of ports which we are going to use further in this section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nw8dZLO9Ajfy2xlwNAHf_A.jpeg" /><figcaption>Motherboard. Detailed View (<em>Image by author</em>)</figcaption></figure><p>The MoBo instruction is useful when you install components. Definitely take a look at it!</p><h3>CPU</h3><p>Now let’s unbox a CPU. The CPU box contained a CPU chip itself and a basic CPU cooler which actually holds most of the space in the box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4C5F3gLnTKg2BQgwgxbjJQ.jpeg" /><figcaption>CPU Unboxing (<em>Image by author</em>)</figcaption></figure><p>We are going to install the CPU into the special CPU socket on the MoBo. It has AM4 format in my setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFwpCuYUpjE0QWZvnin5dQ.jpeg" /><figcaption>CPU Socket (<em>Image by author</em>)</figcaption></figure><p>Be super careful with CPU pins. They are very tangible. Notice that there is also a little golden arrow on one of the edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOlEunv7mQOc8VG4qNogcg.jpeg" /><figcaption>CPU Pins (<em>Image by author</em>)</figcaption></figure><p>It’s there to guide you on how to connect your CPU. There is <strong>only one way</strong> pins can be installed into the socket. It’s when the golden arrow banded edge is in the bottom left corner of the CPU retention plate.</p><p>Push a retention lever down and outward to release the CPU retention plate and put your CPU in the mentioned way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usyYZUN-_QyllIylFsMr6g.jpeg" /><figcaption>Installed CPU (<em>Image by author</em>)</figcaption></figure><p>Push the retention lever back to firmly install your CPU chip.</p><h3>SSD</h3><p>NVMe SSDs are much smaller than their SATA friends. It’s just a one little plane that sits in the box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7vmP8vWDmcFB_wUKXjJNQ.jpeg" /><figcaption>M.2 SSD Unboxing (<em>Image by author</em>)</figcaption></figure><p>To connect this kind of SSDs, you need to use the M.2 socket. My MoBo has two of them. Each of them is supplied with a pair of a screw and a mounting screw. The MoBo has a few mounting posts for SSDs of different lengths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLMSm5kds3EZSUtZaPFg7g.jpeg" /><figcaption>NVMe SSD Installation. M.2 Screw (<em>Image by author</em>)</figcaption></figure><p>Just pick a mounting post that corresponds to your SSD size, install there a mounting screw and fix the SSD with the remaining screw.</p><h3>RAM</h3><p>RAM planks are easy to install as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CV8lIELvp9BG1RTrL1hJVQ.jpeg" /><figcaption>RAM Unboxing (<em>Image by author</em>)</figcaption></figure><p>Unlock your RAM slots and align your RAM plank with the slot. There is <strong>also only one way</strong> the plank can be firmly installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4brLUtoRYPNCrkZGC3vWuA.jpeg" /><figcaption>RAM Installation (<em>Image by author</em>)</figcaption></figure><p>Notice that your MoBo instruction may specify recommended positions for different number of RAMs. Follow those recommendations!</p><h3>Cooler</h3><p>People suggest <strong>avoiding to apply power</strong> to the CPU before installing its cooling system. CPU may overheat or become weaker.</p><p>My cooler is designed to work with both Intel and AMD CPUs. So the cooler box actually contains much more screws and other details than I needed in this particular build. This is the reason why its back panel has such a bizarre form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4dlLb0KNi64s8HZwGo8rg.jpeg" /><figcaption>Cooler Unboxing (<em>Image by author</em>)</figcaption></figure><p>The first step to install the cooler is to uninstall the stock back panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FHRTVizbmhihQnWRnUV8g.jpeg" /><figcaption>Uninstalling Stock CPU Back Panel (<em>Image by author</em>)</figcaption></figure><p>This back panel is going to be replaced by another one provided with your custom cooler. In my case, I had to assemble a back panel in AMD-compatible way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqwcTLeLZ3UUGFRaimEYoA.jpeg" /><figcaption>Cooler Backplate (<em>Image by author</em>)</figcaption></figure><p>Flip your board around and match screws from your new back panel with the motherboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usyYZUN-_QyllIylFsMr6g.jpeg" /><figcaption>Cooler Backplate Installed (<em>Image by author</em>)</figcaption></figure><p>To finalize the back panel installation, you need to install mounting screws on which the actual cooling system would be joined.</p><p>Next, you could assemble the cooler system. It’s typically needed to attach cooler legs on which it should be screwed down to the back panel. After assembling, try to match your mounting screws to make sure your cooler legs are installed correctly.</p><p>One of the final steps, before you can attach your cooler, is thermal paste installation. I used the “pee” method explained in the video below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-hNgFNH7zhQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-hNgFNH7zhQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-hNgFNH7zhQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d1d1e02a89a0904c2fec1f92c7dfb13/href">https://medium.com/media/1d1d1e02a89a0904c2fec1f92c7dfb13/href</a></iframe><p>When using thermal gel, you need to cover the CPU chip area as much as possible to allow better removal of CPU heat. Bubbles of airs that could pop up during this procedure would hurt.</p><p>Finally, you can attach your cooler to the top of the CPU. Press CPU a bit to distribute your thermal gel well on the surface.</p><p>In addition, make sure that the gel stays on the CPU only as it may damage your MoBo.</p><p>Finally, you can connect the cooler power cable to the nearest port on the MoBo marked as CPU_FAN.</p><h3>PSU and Computer Case</h3><p>A PSU box includes a power unit module and various cables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06s24gvxK6nTqfR1E3QefQ.jpeg" /><figcaption>Power Supply Unboxing (<em>Image by author</em>)</figcaption></figure><p>A computer case is just a metal box with two removable panels on the opposite sides of the box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhhcV_W86BGENT4gNWec2Q.jpeg" /><figcaption>Computer case without glass panel (<em>Image by author</em>)</figcaption></figure><p>On the top side of the box, you can see the front panel of the case. You can have a few more ports there as well as power buttons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeHUP1sSyKA9xHITcgaVwQ.jpeg" /><figcaption>Computer case front panel (<em>Image by author</em>)</figcaption></figure><p>First of all, install the main I/O ports cover that comes with your motherboard into your computer case. Surprisingly, it’s important to make sure that all little latches on the sides of the cover are fully installed and visible on the flip side. Otherwise, they may prevent you from screwing your motherboard down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6IHgWWcZTOAZrXJ8UFAcQ.jpeg" /><figcaption>Three little metal latches on the top side of I/O port cover. You should see them on the all of the sides (<em>Image by author</em>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLi8oLMzJWBUeakfwMbj2Q.jpeg" /><figcaption>Main I/O ports (<em>Image by author</em>)</figcaption></figure><p>Then, you can try to screw down your motherboard to the case mounting positions.</p><p>Next, there are three cables you need to connect in order to power your system:</p><ul><li>Motherboard power cable</li><li>CPU power cable</li><li>Front panel power cable</li></ul><p>It’s straightforward how to connect CPU and motherboard power cables. However, it may be challenging to connect front panel cables for the first time. The following video was helpful in my case:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9--Nbg2qKUA&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9--Nbg2qKUA&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2F9--Nbg2qKUA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2457fcb4bcbf17c5da10fcd0a1b8859b/href">https://medium.com/media/2457fcb4bcbf17c5da10fcd0a1b8859b/href</a></iframe><p>There may be still a few remaining cables to connect to the MoBo. In my case, I had USB, audio and Type-C power cables. The first two I was able to connect while the last one required an adapter since my MoBo doesn’t have Type-C ports. So I kept it disconnected. By the way, PCPartsPicker can warn you about such an issue in advanced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Pv0R_ezcxujT9-ktKel0w.jpeg" /><figcaption>Motherboard installed into the computer case (<em>Image by author</em>)</figcaption></figure><p>Additionally, you may need to connect coolers which come with your computer case.</p><p>At this point, you may try to apply power to your PC but you will get <strong>no video signal</strong> until you install your graphic card.</p><h3>GPU</h3><p>The GPU box includes a card itself and an instruction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InSNL36xb9KAJgGYFRfzWw.jpeg" /><figcaption>RTX 3070 Graphic Card (<em>Image by author</em>)</figcaption></figure><p>My GPU holds two slots, so I needed to match output covers to replace them with actual GPU I/O ports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_S28-CVCvSvm_6uFWsu7Q.jpeg" /><figcaption>Graphic Card Covers on the Computer Case (<em>Image by author</em>)</figcaption></figure><p>GPU ports are HDMIs and DPs with mocks to protect them from the dust. On the left side of the I/O steel plate you can see two teeth that help to mount the graphic card.</p><p>Make sure to <strong>use one of these ports to connect your monitor</strong>. HDMI port on the motherboard may not work properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dg0V3HA1pg1zznziaTyJpw.jpeg" /><figcaption>Ports on Graphic Card (<em>Image by author</em>)</figcaption></figure><p>The computer case has special slots for these teeth. If you find that <strong>your GPU teeth cannot be installed</strong>, you most likely have some issues with motherboard mounting. Try to remount your motherboard to match the slots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lG7md7oe50RyzPf0m-VuoA.jpeg" /><figcaption>Graphic Card Teeth Mounted (<em>Image by author</em>)</figcaption></figure><p>Gigabyte Aorus Master RTX 3070 requires two VGA cables to power it. Make sure the ends of your cables are firmly installed into the GPU and PSU. Otherwise, the GPU may be not found by the motherboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9yk6QqqgZ1sOYUQe-qpmw.jpeg" /><figcaption>Power applied to the graphic card (<em>Image by author</em>)</figcaption></figure><h3>Hardware Troubleshooting</h3><p>If you put your first custom PC together, it’s plausible that it’s not going to work from the first try. In my case, the workstation simply did not turn on. There are a few things you want to double check before returning your parts back to your suppliers:</p><ul><li><strong>The front panel power is connected correctly</strong>. Get back to <a href="https://www.romaglushko.com/blog/how-i-built-my-ml-workstation/#how-to-install-front-panel-power-cables">the front panel power cable installation</a> and double check if you get them installed the right way. For instance, this was the reason why my PC did not work.</li><li><strong>RAM sticks are seated securely</strong>. Try to reinstall your RAM sticks. RAM port mechanism should lock them down.</li><li><strong>Power supply cables are connected firmly</strong>. Make sure your power cables are fully connected on both sides. I had some issues with this as well. Each connector has a plastic lock mechanism that should hold cables inside of the ports. Check if all locks are activated.</li><li><strong>The motherboard is installed on the standoffs</strong>. Some cases provide a special standoff screws on which motherboard should be installed. Standoffs elevate the motherboard and protect it from touching metal trays which may lead to the short out.</li></ul><p>Onother symptoms I want to review is <strong>your PC turns on but shuts down after short time during booting</strong>. In this case, there may be faulty components that prevent your PC build from running. I found a good strategy to diagnose this kind of issues:</p><ul><li>Try to unplug all “unnecessary” components like second HDD or case coolers and double check whenever the issue is still in place.</li><li>Keeps unconnecting things until your issue is not there anymore.</li><li>The last unconnected component is likely the reason for the issue. Try to connect it again to prove the assumption.</li></ul><p>The following video shows the process of troubleshooting in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQP6pAPctqbk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQP6pAPctqbk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQP6pAPctqbk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/99c9d4da7cb89b2eaf38aa883a8bd1d8/href">https://medium.com/media/99c9d4da7cb89b2eaf38aa883a8bd1d8/href</a></iframe><p>Also, your motherboard may have debug LEDs which indicate what components in the system are not found. In this case, you need to double check that signalled components are getting power and installed correctly.</p><p>Finally, after some time you will be able to see a video signal on your screen and system that is looking for a bootable device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Khc6fcsIe1z-mSEj_Mx6Q.jpeg" /><figcaption>PC Boot and back side of the case with cable management sections (<em>Image by author</em>)</figcaption></figure><p>It’s a good time to mount your PSU and take advantage of the cable management system that your computer case provides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmgJMB7GB2WOY_KlveuOeQ.jpeg" /><figcaption>Mounted PSU (<em>Image by author</em>)</figcaption></figure><h3>Software Installation</h3><p>I considered Ubuntu 20.10 and Windows10 + WSL2 setups. Linux setup is more stable and straightforward now. However, WSL2 sounds to be a pretty viable way to go as well. Tell you more about that next time.</p><p>I have only macOS at my hand, so I used <a href="https://unetbootin.github.io/">the UNetBootIn application</a> to burn a Linux bootable USB. I preferred to use <a href="https://ubuntu.com/download/alternative-downloads">a BitTorrent</a> to download the Ubuntu 20.10 image.</p><p>Pay attention, that some Linux distributions (like Kali) complain that UNetBootIn <strong>is not the most reliable way</strong> to write a bootable USB. Fortunately, I seemed to have no issues with that. However, I had to buy a new USB stick as my old one seems to become faulty. Installation from the old USB stick failed because of the broken files every other time I had tried to install an OS.</p><p>After I got a new USB stick, I could able to install Ubuntu without issues.</p><h3>WiFi Adapter Drivers</h3><p>Unfortunately, MSI X470 MAX Gaming Plus motherboard doesn’t support WiFi out-of-the-box. I did not want to mess around with Ethernet cables, so I bought a TP-Link Archer T2U WiFi adapter. The issue is that Ubuntu doesn’t support it and there is a need for additional drivers.</p><p>The good news is that TP-Link devices have good support in the Linux community, so I was managed to find needed drivers quickly. Namely, I installed <a href="https://github.com/aircrack-ng/rtl8812au">the rtl8812au drivers</a>. To install these drivers, you need to have the Internet connection, because they depend on DKMS package which is surprisingly doesn’t installed in vanilla Ubuntu. Follow the instruction provided in the driver repository to install it. Make sure that sudo make dkms_install command went without errors.</p><p>In addition, you may want to reboot your machine in order to double check that drivers work in that case. If not, follow <a href="https://askubuntu.com/questions/1184993/driver-for-rtl8812au-unplugs-after-reboot">this answer on StackOveflow</a>. Also, I had to run sudo make dkms_install command the second time to finally get drivers work after rebooting.</p><h3>CUDA Setup</h3><p>Leveraging my new GPU resource required CUDA to be configured.</p><p>CUDA is a parallel computing platform from NVIDIA that allows to fully leverage advantages of CUDA-enabled graphic cards. In general, the process of installing can be divided into 3 parts:</p><ul><li><strong>Installing graphic card drivers</strong>. The recommended way to install NVIDIA drivers in Ubuntu is through Software &amp; Update application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*EBgWpjp3kwNJQXHMc1k47A.jpeg" /><figcaption>NVIDIA Drivers Installation in Ubuntu (<em>Image by author</em>)</figcaption></figure><ul><li><strong>Install CUDA Toolkit</strong>. NVIDIA has <a href="https://developer.nvidia.com/cuda-downloads?target_os=Linux&amp;target_arch=x86_64&amp;=Ubuntu&amp;target_version=20.04&amp;target_type=deb_network">a sweet wizard</a> that can generate installation commands for your system. Execute all commands that it suggests you.</li><li><strong>Install cuDNN</strong>. cuDNN is a GPU-accelerated library with primitives for deep learning. You need to be registered in <a href="https://developer.nvidia.com/cudnn-download-survey">NVIDIA Developer Program</a> in order to access the library. In the end, you will be landed on a page where you can download <strong>cuDNN Runtime and Developer libraries</strong> as well as <strong>Code Samples and User Guide</strong>. I downloaded all three of them as deb packages and installed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXzpaUCvXmUrr5BFuAtxzw.png" /><figcaption>Download cuDNN page (<a href="https://developer.nvidia.com/cudnn-download-survey">access is here</a>) (<em>Image by author</em>)</figcaption></figure><p>Here is <a href="https://docs.nvidia.com/deeplearning/cudnn/install-guide/index.html#install-linux">the official installation guide</a> from NVIDIA.</p><p>So far I have tested my setup in PyTorch project. There may be another thing that would bother you. I had to reinstall my PyTorch libraries in order to leverage my GPU device. This time PyTorch has <a href="https://pytorch.org/get-started/locally/">a smooth installation wizard</a> which can help you with that.</p><p>Finally, if you use <a href="https://www.pytorchlightning.ai/">PyTorch Lightning</a>, it’s a matter of changing <a href="https://pytorch-lightning.readthedocs.io/en/stable/advanced/multi_gpu.html#select-gpu-devices">gpus config</a> for your trainer instance and it will use all your GPU resources during training or inference.</p><h3>Workflow</h3><p>Currently, I’m using the simplest possible workflow based on the sFTP connection to my machine and <a href="https://www.jetbrains.com/help/pycharm/deployment-in-PyCharm.html#automatic-upload">changes auto-uploading feature from PyCharm Professional</a>.</p><p>In order to connect my deep learning workstation, I installed <a href="https://www.cyberciti.biz/faq/how-to-install-ssh-on-ubuntu-linux-using-apt-get/">OpenSSH server</a> there. I like to disable the password authentication in favor of SSH key usage. Also, it’s a good idea to change the default 22 port to something else.</p><p>Once the SSH connection is ready, you can setup deployment host in your PyCharm instance and install your project on the ML workstation. This is needed for the first time setup of a project and it’s handy to do it by running git clone plus poetry install commands. Rsync is a quick way to upload datasets into your machine.</p><p>Most changes you do in PyCharm will be automatically synced on the deep learning machine. When you are ready to test your changes, you can execute your project by running a command via SSH in the ML workstation.</p><p>With this workflow, you can still work from your MacBook, while running the code in the GPU-accelerated computer.</p><h3>Summary</h3><p>It’s awesome to see how a small idea of having some GPU resource at my hand grown in the entire project!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJ6oYg9e3H6te5a5z5iFPA.jpeg" /><figcaption>My Deep Learning Workstation 1.0 (<em>Image by author</em>)</figcaption></figure><p>I hope this article will be helpful when you build your own deep learning workstation. Be sure to let me know if this is true in the comments below!</p><p>Most likely I will be experimenting with other workflows and the current setup in the following weeks to see how they work for me, so stay tuned and good luck on building your own ML beasts.</p><p>This post was originally published on <a href="https://www.romaglushko.com/blog/how-i-built-my-ml-workstation/">my website</a>.</p><h3>References</h3><ul><li><a href="https://timdettmers.com/2018/12/16/deep-learning-hardware-guide/">A Full Hardware Guide to Deep Learning</a></li><li><a href="https://timdettmers.com/2020/09/07/which-gpu-for-deep-learning/">Which GPU(s) to Get for Deep Learning: My Experience and Advice for Using GPUs in Deep Learning</a></li><li><a href="https://pcpartpicker.com/user/tim_dettmers/saved/#view=mZ2rD3">Deep Learning Barebones on PCPartPicker</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f799c1de0341" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-i-built-my-ml-workstation-f799c1de0341">How I built my ML workstation 🔬</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power of No Action]]></title>
            <link>https://roma-glushko.medium.com/power-of-no-action-thought-76959155749e?source=rss-2607aea71af1------2</link>
            <guid isPermaLink="false">https://medium.com/p/76959155749e</guid>
            <category><![CDATA[management]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[life-experience]]></category>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[psychology]]></category>
            <dc:creator><![CDATA[Roma Glushko ]]></dc:creator>
            <pubDate>Wed, 28 Apr 2021 10:10:16 GMT</pubDate>
            <atom:updated>2021-04-28T10:10:16.198Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u9yzKEwSJ8My90qLHa-wjg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ianhutchinson92?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ian Hutchinson</a> on <a href="https://unsplash.com/@ianhutchinson92?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Being decisive is good. Although taking rush actions without deep consideration of bad outcomes can be destructive. Often our life gives us a situation when the best possible move is to take no action.</p><p>You have a few thousands of bucks and you want to invest. You consider buying some gold. You realize that there may be a problem to find a way to sell this metal later. What should you do? You can think more about possible ways to sell. You can review other types of investments. Other things being equal, your best current decision is to buy no gold. No action. It is your null hypothesis.</p><h3>Null Hypothesis</h3><p>In statistics, they realized that people are famously bad at making decisions based on gut feeling. Even some data at hand can’t certainly help. What they proposed is a simple framework called A/B testing. So you have the current state A and you want to know if a new state B is better in some sense than A. Then you collect your data.</p><p>The most important matter happens next. If you want to be fair and unbiased, you need to assume that A is better than B. From this point, you are free to look for proofs in your data that helps you to retract this assumption and prove that B is better than A.</p><blockquote>No action is a reasonable default until you see better options.</blockquote><h3>Zugzwang</h3><p>In chess, there is a beautiful situation called zugzwang. When you are in zugzwang, your best move is to make no moves. All your possible moves would make your position significantly weaker.</p><p>In chess, there is the compulsion to make a move. In real life, there is often not. Real life is much more multi-faceted than the game.</p><p>So take your time to think deeper. No rush. No action yet.</p><blockquote><em>The original article was posted on </em><a href="https://www.romaglushko.com/thoughts/power-of-no-action/"><strong><em>my website</em></strong></a><em>. Go and check it out!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76959155749e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Nearest Neighbors]]></title>
            <link>https://roma-glushko.medium.com/k-nearest-neighbors-1c5e611b4f8a?source=rss-2607aea71af1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c5e611b4f8a</guid>
            <category><![CDATA[nearest-neighbors]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[knn-algorithm]]></category>
            <dc:creator><![CDATA[Roma Glushko ]]></dc:creator>
            <pubDate>Tue, 27 Apr 2021 12:27:54 GMT</pubDate>
            <atom:updated>2021-04-27T12:27:54.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rhWE5096XVNi8Rd6C53cg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@olliecraig1?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Ollie Craig</a> from <a href="https://www.pexels.com/photo/roads-with-vehicles-near-buildings-and-autumn-trees-in-city-6398503/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>K-Nearest Neighbors (a.k.a KNN) is one of the famous machine learning approaches. It’s simple, intuitive and useful tool to have in your machine learning toolbox.</p><p>KNN is instance-based learning algorithm. It doesn’t make any assumption about dataset relations and uses provided samples in order to estimate new items.</p><h3>Intuition</h3><p>As old saying goes, you are who you surround yourself with. This idea even has mathematical interpretation. In N-dimensional space, points that are closer to each other are more similar, then ones that stand apart. This is the assumption that KNN algorithm makes. It tries to find K nearest known points or samples, also called “neighbors”, to some unknown sample. Majority class of neighbors defines class of the unknown sample.</p><figure><img alt="Nearest neighbors defines class of unknown sample" src="https://cdn-images-1.medium.com/max/756/1*27M1mIXgm7u2ZZaGjiIZNA.png" /><figcaption>Nearest neighbors defines class of unknown sample</figcaption></figure><p>To came from this idea to implementation, we need to define how to find closest points.</p><h3>Closest Points</h3><p>We need to somehow measure distance between samples in order to find closest (hence similar) neighbors. Turned out there are quite a few metrics we can use:</p><ul><li><a href="https://en.wikipedia.org/wiki/Euclidean_distance">Euclidean Distance</a> — straight-line distance between two points</li><li><a href="https://en.wikipedia.org/wiki/Taxicab_geometry">Manhattan (City Block) Distance</a> — distance between two points traversed along one axis at the time at right angle</li><li><a href="https://en.wikipedia.org/wiki/Minkowski_distance">Minkowski Distance</a> — Generalization of Euclidean and Manhattan distances</li><li>scikit-learn supports <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.DistanceMetric.html#sklearn.neighbors.DistanceMetric">other metrics</a> as well</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-PbWcqX7EH3R1gQCGMUIjQ.png" /><figcaption>Distance metrics and their boundaries in 2D</figcaption></figure><p>Euclidean and Manhattan distances are two the most popular distance metrics:</p><figure><img alt="Euclidean and Manhattan distances" src="https://cdn-images-1.medium.com/max/736/1*ItK-APk8AXGdnw_rSwS1Dw.png" /></figure><p>where x=(x1, x2, …, xn) and y=(y1, y2, …, yn) are two points in the N-dimensional space.</p><p>Minkowski distance incorporates both Euclidean (when p is 2) and Manhattan (when p is 1) distances and gives additional degree of flexibility via p param:</p><figure><img alt="Minkowski distance" src="https://cdn-images-1.medium.com/max/854/1*sRN3NRiDMPqM_p3eTF38Eg.png" /></figure><p>These distance metrics are intuitive and fast to compute.</p><p>However, all features or dimensions are treated the same way. This may be an issue if features have values in different scales. For example,</p><ul><li>customer age value is normally between 18 and 100</li><li>annual income values lies between 20,000 and 200,000 (and sometimes goes far beyond)</li></ul><p>When calculating distance metrics, this leads to a situation when major part of similarity actually comes from large scale-value features (like annual income). As a result, the rest of the features will be almost neglected and won’t be really taken into account during similarity checking.</p><h3>Standardization</h3><p>Ignoring small-scale features in the similarity checking is rarely a desired effect. We would like rather to avoid it to get real neighbors of our sample.</p><p>We can try to rescale all features to the same range (0–1, for example). This will standardize or normalize features and let them have the same influence in the distance calculations.</p><figure><img alt="Z-score" src="https://cdn-images-1.medium.com/max/304/1*YtaQJP688hMTA4cIAcwwNA.png" /></figure><p>where x is sample feature value, x― is a feature mean and S is a feature standard deviation.</p><p>Z is a <a href="https://en.wikipedia.org/wiki/Standard_score">standard score (or z-score)</a> of the sample feature value. It’s a dimensionless quantity and it shows how “unusual” or far sample feature value from the feature mean (which is usual or expected value).</p><p>Though normalization changes values of features, it doesn’t change feature distribution shape.</p><h3>Dense Dataset</h3><p>We assume that similar samples are close in the N-dimensional feature space. Is this always a case?</p><p>Turned out that with growing number of dimensions (or features), number of samples should grow exponentially in order to keep the same density of sample points in the space. High-dimensional space contains far more actual space between points then our intuition may suggest.</p><p>This may lead to a situation when distance to neighbors across all feature axis are just slightly bigger then average distance between points. In sparse high-dimensional feature space we are loosing our notion of nearest points.</p><p>This is the reason why ratio of features to samples is important for KNN algorithm.</p><h3>Neighborhood Size</h3><p>Effectiveness of applying KNN depends greatly on choosing appropriate size of neighborhood a.k.a <strong>K</strong> hyperparam. In turn this choice is determined by dataset. It’s usual to see K in range from 1 to 20 (5 is default size in scikit-learn).</p><p>Smaller value of K adds more sensitivity and variance. For noisy datasets this means that given a slightly adjusted dataset we may get a different neighbors.</p><p>Increasing K hyperparam adds more bias to KNN results and smoother decision boundaries. If K param value is too big, KNN will loose its ability to find local structures in the dataset.</p><p>In general, neighborhood size is subject of hyperparam tuning. Final decision should be validated on separated validation dataset.</p><h3>Applications</h3><p>You may find KNN-based classificators and regressors which is a trivial application of KNN idea. Let’s review a few less obvious applications where KNN shines even better.</p><h4>Feature Engineering</h4><p>KNN is able to identify local structures in the dataset. This information is useful clue itself and local structure labels may be used in classification/regression pipeline as an additional feature.</p><h4>Neighbors in Embeddings</h4><p>KNN algorithm becomes useful when you have embeddings — samples projected into lower dimensional latent space. In embedding space distance means similarity and KNN can suggest similar items. This is especially useful for recommendation systems. In that case, nearest neighbor search can be optimized further by leveraging <a href="https://en.wikipedia.org/wiki/Locality-sensitive_hashing">locality-sensitive hashing</a>, for instance.</p><h4>Anomaly Detection</h4><p>Distances to K nearest neighbors can be viewed as an estimation of local density. If distance is relatively large, this implies that density is low and sample is likely to be an outlier.</p><h3>Summary</h3><p>I hope we shed a bit of light on theoretical aspects of K-Nearest Neighbor algorithm and proved that this pure idea is still useful after decades of being formulated.</p><blockquote>The original article was posted on <a href="https://www.romaglushko.com/blog/k-nearest-neighbors/"><strong>my website</strong></a>. Go and check it out!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c5e611b4f8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>