Bishwas Regmi
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- type: article title: ThingsBoard - Distribution Analysis date: 2021-03-29T16:30:00+02:00 draft: false # set to false if your team gives consent to publish this post publicly --- # ThingsBoard - Distribution Analysis After providing and gaining much deeper insight into ThingsBoard's IoT platform and architecture[^tbdesosa], we now present a deeper analysis of ThingsBoard's most exciting aspect: the distribution architecture. [^tbdesosa]: https://2021.desosa.nl/projects/thingsboard/ ## Distributed Components To recap, ThingsBoard consists of six main distributed components which are, (IoT) devices, ThingsBoard Transport microservices, Thingsboard Core microservices, ThingsBoard Rule Engine microservices, ThingsBoard Web UI and Third-Party systems. <!-- ![](https://i.imgur.com/50bfJFm.png) --> {{<image file="essay4picture1.png" caption="ThingsBoard Architecture">}} *Devices* represent the range of various types of IoT devices which can be connected to ThingsBoard such as, thermostats, sensors, gps trackers, etc.\ *ThingsBoard Transport microservices* is the collection of transport servers which responsible for transporting the data from the IoT device to the ThingsBoard Core. This includes the HTTP [^HTTP2], MQTT [^MQTT] and CoAP [^COAP] servers. \ *ThingsBoard Core microservices* consists of core node(s) responsible for handling REST API calls, websocket subscriptions, process messages from devices via Rule Engine and monitor connectivity state of the devices. \ *ThingsBoard Rule Engine microservices* include configurable chain of rules that are used to process incoming messages from the devices. They also include JavaScript Executor Microservices which allows users to add custom JavaScript functions to process incoming data. \ *ThingsBoard Web UI* allows users to interact with the system by letting them visualize the devices data and configure the rule engine. \ *Things-Party systems* entails databases (Cassandra, PostgreSQL), queuing software (Apache Kafka), data structure storage for caching (Redis) and distribution coordination servers (ZooKeeper).[^explanation] A more in-depth analysis of these components can be found in one of our previous essays titled 'ThingsBoard - Architecture'.[^essay2] [^explanation]: https://thingsboard.io/docs/reference/msa/#third-party [^essay2]: https://2021.desosa.nl/projects/thingsboard/posts/2.-architecture/ ## Inter-component Communication In this section, we will look at how the components communicate with each other and what information is exchanged between them. <!-- ![](https://i.imgur.com/k23ZKuS.png) --> {{<image file="essay4picture2.png" caption="ThingsBoard microservice Architecture">}} ### Communication between Devices and ThingsBoard Transport Microservices ThingsBoard Transport Microservices consist of HTTP(S), MQTT and CoAP server nodes. There can be multiple instances of each server if the number of devices is high. In that case, a load balancer(HA Proxy[^haproxy]) is used to distribute the server requests. The devices can use standard client libraries for the protocol they use to communicate with their respective servers. For authentication, *access tokens* are used. The access tokens are automatically generated when a new device is registered on the WEB UI or through automated device provisioning.[^PROV] [^HTTP2] [^MQTT] [^COAP] By default, ThingsBoard expects the data from devices to be in JSON format. However, it is also possible to change this format to Protocol Buffer or Protobuf[^protobuf] by changing the device payload parameter to Protobuf. The code to do this is shown below, in line 6. Protocol Buffer is a language and platform-neutral way of serializing structured data. By serializing the data, the size of transmitted data is minimized.[^PROTO] ```java= case DeviceTransportType.MQTT: const mqttTransportConfiguration: MqttDeviceProfileTransportConfiguration = { deviceTelemetryTopic: 'v1/devices/me/telemetry', deviceAttributesTopic: 'v1/devices/me/attributes', // Configure Transport Payload type transportPayloadTypeConfiguration: {transportPayloadType: TransportPayloadType.PROTOBUF} }; ``` The information that is exchanged between the de devices and Transport microservices is mainly telemetry data from the devices like temperature, GPS position, energy consumption, etc. Below is an example of how an MQTT device publishes its telemetry data to its server using a message string and a JSON file. Besides telemetry data, device attribute updates and connectivity status data are also exchanged. They follow the same messaging format. ```sh= # Publish telemetry data myMQTT_device -d -q 1 -h "thingsboard.cloud" -t "v1/devices/me/telemetry" -u "$ACCESS_TOKEN" -m "{"temperature":42}" # Publish telemetry data from file myMQTT_device -d -q 1 -h "thingsboard.cloud" -t "v1/devices/me/telemetry" -u "$ACCESS_TOKEN" -f "telemetry-data-as-object.json" ``` [^haproxy]: http://www.haproxy.org/ [^HTTP]:https://www.w3.org/Protocols/rfc2616/rfc2616.txt [^MQTTandCoAP]:https://www.eclipse.org/community/eclipse_newsletter/2014/february/article2.php#:~:text=MQTT%20and%20CoAP%20are%20both,clients%20through%20a%20central%20broker.&text=CoAP%20is%2C%20primarily%2C%20a%20one,information%20between%20client%20and%20server. [^HTTP2]:https://thingsboard.io/docs/reference/http-api/ [^MQTT]:https://thingsboard.io/docs/reference/mqtt-api/ [^COAP]:https://thingsboard.io/docs/reference/coap-api/ [^PROTO]:https://thingsboard.io/docs/user-guide/device-profiles/#transport-configuration [^PROV]:https://thingsboard.io/docs/user-guide/device-provisioning/ [^protobuf]: https://github.com/protocolbuffers/protobuf#protocol-buffers---googles-data-interchange-format ### Communication between ThingsBoard WEB UI and ThingsBoard Core Microservices The comminication between the WEB UI and ThingsBoard Core Microservices is done using WebSockets API which uses the WebSocket protocol that opens a bi-directional interactive communication session. The WebSockets API[^socket] gives access to all the functionalities of the REST API and also allows to directly open a connection to Telemetry data service and subscribe to data updates. [^socket]: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API ### Queues : Communication between the rest of the components Aside from the devices, the rest of the distributed components use queues to communicate with each other. Apache Kafka is used by default to implement queues. Kafka is a distributed, reliable and scalable persistent message queue and streaming platform.[^KAFKA] However, other queue imeplementation including RabbitMQ, AWS SQS, Azure Service Bus, Google Pub/Sub and more are also supported. The messages in the queue are serialized using Protocol Buffers. So, if the devices use JSON format for messages, they are serialized before arriving at the queue and vice-versa. The queues are implemented with an abstraction layer which contains topics and partitions. Topics allow components to be isolated from each other and run asynchronously, which enables distribution of a system. Message producers push their message to a certain topic and the consumers of the topic pull the messages. Partitions of a topic allow for a higher message processing throughput. This is because, partitioning divides/duplicates a topic into several replicas so that multiple consumers can pull a message from multiple topic partitions at the same time. Each partition of a topic can also be placed on a different machine, which also contributes to better distributability of the system. Below is a figure[^KAFKAPICTURE] to illustrate how the partitions of a topic are used. <!-- ![](https://i.imgur.com/4ftLnP7.png) --> {{<image file="essay4picture3.png" caption="Schematic overview of paritions">}} [^KAFKAPICTURE]:https://scalac.io/blog/what-is-apache-kafka-and-what-are-kafka-use-cases/ <!-- The configuration of a topic is done in the configuration file 'thingsboard.yml'. Below is a code snippet showing the configuration of the topic 'tb_core' as an example. We can see that the topic in its current configuration has 10 partitions. We can also see that the topic has other configurations as well, such as the polling interval and pack processing timeout. ```yml= core: topic: "${TB_QUEUE_CORE_TOPIC:tb_core}" poll-interval: "${TB_QUEUE_CORE_POLL_INTERVAL_MS:25}" partitions: "${TB_QUEUE_CORE_PARTITIONS:10}" pack-processing-timeout: "${TB_QUEUE_CORE_PACK_PROCESSING_TIMEOUT_MS:2000}" usage-stats-topic: "${TB_QUEUE_US_TOPIC:tb_usage_stats}" stats: enabled: "${TB_QUEUE_CORE_STATS_ENABLED:true}" print-interval-ms: "${TB_QUEUE_CORE_STATS_PRINT_INTERVAL_MS:60000}" ``` --> Next, we will discuss the topics that are used for communication between the components. A list of the used topics is given below. The topics are catagorized according to their corresponding service type. - transport : - tb_transport.api.requests - tb_transport.api.responses - tb_transport.notifications - core : - tb_core - tb_usage_stats - rule engine : - tb_rule_engine.main - tb_rule_engine.hp - tb_rule_engine.sq - js executor : - js_eval.requests - js_eval.responses The topic 'tb_transport.api.requests' is used to execute transport server API call in order to check device credentials or register new devices. The responses to the API calls are published on 'tb_transport.api.responses'. These topics are used to exchange information between Core microservices and Devices via Transport microservices. 'tb_transport.notifications' is used for high priority notifications coming from devices that require minimum latency and processing time. The topic 'tb_core' is used to publish messages from Rule Engine microservices and devices via. Transport microservices to Core microservices. The published messages include session lifecycle events, attributes, RPC subscriptions, etc. When a cluster of ThingsBoard Core nodes are used, they also use this topic to communicate with each other.[^NODES]. 'tb_usage_stats' is used to report the usage statistics of the Core microservices. The topic 'tb_rule_engine.main' is used to publish messages from Core microservices and Transport microservices to the Rule engine. The messages include telemetry data, device states, entity lifecycle events, etc. to be processed by the Rule Engine microservices.'tb_rule_engine.hp'is used for high priority messages. 'tb_rule_engine.sq' is used for messages that have to be processed in a sequence set by the originator. A message can thus only be processed if there is an acknowledgment of the preceding message in the sequence being finished. The topic 'js_eval.requests' is used to process messages using custom user defined JavaScript functions. Its function is similar to the Rule Engine microservices and involves the same message types. [^KAFKA]:https://thingsboard.io/docs/reference/msa/#transport-microservices [^QUEUE]:https://thingsboard.io/docs/reference/#message-queues-are-awesome [^NODES]:https://thingsboard.io/docs/reference/msa/#thingsboard-node ## Fault Tolerence ThingsBoard claims to be fault-tolerant as it has “no single-point-of-failure, every node in the cluster is identical”. The following section will investigate this claim and how the different components of ThingsBoard handle faults. <!-- The data from the client devices is sent to the ThingsBoard Core and Rule engine. The first error that could occur is faulty data from the sensors. Although this is outside the hands of ThingsBoard, a safety net could be placed to detect faulty data by setting an upper and lower bound to data which could be sent. This data is transported using the MQTT, HTTP and CoAP nodes. MQTT is intially designed for unreliable networks and thus fault-tolerant by design. This fault-tolerance is realised by using redundant and power-fail-safe file systems.[^MQTTSAFETY] --> The message queues form a critical part of the system. For the reliability of ThingsBoard, it is very important that the message queues are tolerant to faults, losses and crashes. The default message queue used by ThingsBoard is Apache Kafka. Fault-tolerance is natively embedded in Kafka. This fault-tolerance is achieved by highly available and replicated partitions, a schematic overview can be found under this section. If a task runs on a machine which fails, this task is automatically restarted by the Kafka streams in one of the remaining running instances of the application. In order to make the partitions also robust to failure, each partition maintains a replicated changelog Kafka topic in which any state updates are tracked. Even if a task crashes on a machine and is restarted on another machine, the Kafka Streams guarantees to restore their associated states by replaying the changelog topics prior the failure. Via this way no data is lost and it makes the failure handling completely transparant to the end user. [^KAFKAOFFICIAL] [^QUEUE] [^QUEUESAFETY] <!-- ![](https://i.imgur.com/364xBcY.png) --> {{<image file="essay4picture4.png" caption="Schematic overview Kafka partitions">}} The ThingsBoard core microservice is one of the most important component of the system and requires to be resistent against errors. The core is using the Actor System [^ACTOR] and which is implemented over different nodes. The partitions of the incoming messages are handled by the responsible nodes. [^COREFAULT] In this case are the actors the tenants and devices. The actors divide their tasks into smaller subtasks by starting child actors. By splitting the tasks into small pieces, failures only have a very small effect and do not propagate in the hierachy allowing for a safe and fault proof behaviour. The default database used by ThingsBoard is PostgreSQL. The nature of this database falls in line with rest of ThingsBoard as also this system is designed to be fault-tolerant. It makes use of multiple servers or nodes which make up a cluster. The node that allows a user to make changes is known as the primary node and can be seen as the source of changes. The database server which allows read-only access is called the stand-by node. The key aspect of replication is transferring the data captured by the primary node to the different nodes. In PostgreSQL, the primary node sends the data to the WAL (Write-Ahead Logging)[^WAP], which can be seen as a log file. Then, the data is fetched from the WAL and stored in the stand-by nodes. To improve efficiency and availablity, different modes of stand-by nodes are used. An overview can be found under this section. | WAL Level | Suitable for | | -------- | -------- | | minimal | crash recovery | | replica | physical replication/ file-based archiving | | logical | logical replication | In case a primary node crashes, one of the standby nodes is promoted to momentarily take its place. Depending on the duration and severity of the crash, a Switchover (temporarily switch the primary node) or a Failover (permanent promotion) is possible.[^POSTGRESQL] [^MQTTSAFETY]:https://www.automationworld.com/factory/iiot/article/21174207/designing-faulttolerant-iiot-systems [^QUEUESAFETY]:https://jack-vanlightly.com/blog/2018/8/31/rabbitmq-vs-kafka-part-5-fault-tolerance-and-high-availability-with-rabbitmq [^MONOLITH]:https://thingsboard.io/docs/reference/#monolithic-vs-microservices-architecture [^KAFKAOFFICIAL]:https://kafka.apache.org/0102/documentation/streams/architecture#:~:text=Kafka%20Streams%20builds%20on%20fault,needs%20to%20re%2Dprocess%20it. [^POSTGRESQL]:https://www.2ndquadrant.com/en/blog/evolution-of-fault-tolerance-in-postgresql-replication-phase/ [^WAP]:https://en.wikipedia.org/wiki/Write-ahead_logging [^ACTOR]:https://doc.akka.io/docs/akka/current/general/actor-systems.html [^COREFAULT]:https://thingsboard.io/docs/reference/#:~:text=ThingsBoard%20Core%20is%20responsible%20for%20handling%20REST%20API%20calls%20and%20WebSocket%20subscriptions.&text=ThingsBoard%20Core%20uses%20Actor%20System,partitions%20of%20the%20incoming%20messages. ## Trade-offs of Distributed system In order to discuss the trade-offs of ThingsBoard being a distributed system, we will use the CAP Theorem. CAP stands for Consistency, Availablility and Partition tolerance, which are the three core desired properties of a distributed system.[^CAP1] The CAP theorem states that only two of these three properties can be achieved simultaneously, so there must be a trade-off. Below is the definition of these properties. - (Strong) Consistency : Each read contains the most recent write or gives an error - Availibility : Each read request gets a non-error response, which does not have to contain the most recent write - (Network) Partition tolerence : The system can continue functioning even if some messages are dropped or delayed in the network We always want our distributed system to be partition tolerant. Depending on how Partition tolerence is implemented, only either Strong Consistency or Availability can be achieved. In the case that the system just cancels a process and returns an error due to a message drop or delay, then only Consistency is achieved. If the system continues to run the process with older available data, then the system is Available but not Consistent. The main communication method used by the core components of ThingsBoard is Kafka queues with topic partitions, as discussed in previous section '**Queues : Communication between the rest of the components**'. Kafka guarantees that published messages to a topic are kept in a log in the order they are sent, and only after all partitions recieve the message and put it in their log, the published message is considered 'commited'.[^CandA] So, we can say the ThingsBoard favors Availability over Strong Consistency as messages can be delayed when waiting for all topic partitions to be synced. As for consistency, Sequential consistency is still achieved as the order of the messages in all partitions are still preserved. [^CAP1]:https://dl.acm.org/doi/10.1145/564585.564601 [^CandA]: https://sookocheff.com/post/kafka/kafka-in-a-nutshell/#:~:consistency%20and%20Availability ## References

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully