Jo
    • 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
    • Engagement control
    • 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 Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    ## OakNorth Growposium :seedling: Code and Knowledge Cultivation with Bulbasaur Insights ![image](https://hackmd.io/_uploads/rJz50pWua.png) --- # SNS and SQS --- ## What are SQS and SNS? --- <img src="https://i.imgflip.com/88kjwn.jpg" title="made at imgflip.com"/> --- Spot the difference :female-detective: ![What is Amazon SNS?](https://hackmd.io/_uploads/r1wVQ_JL6.png) ![What is Amazon SQS?](https://hackmd.io/_uploads/r1ayNKWdp.png) --- **Both are**: - parts of Amazon Web Services (AWS) - message related services :incoming_envelope: - Exist to help event-driven and cloud-based systems :cloud: - 'Simple ... Service' - Often used together :handshake: --- Simple NOTIFICATION Service A 'push' technology <!-- services are configured to 'pull' from SQS --> <img src="https://hackmd.io/_uploads/ByOY-O18a.png" height="300px"/> --- Simple QUEUE Service A 'pull' technology (services are configured to 'pull' from SQS) <img src="https://hackmd.io/_uploads/SkZTzO186.png" height="300px"/> --- ## SNS Simple Notification Service --- ## Before SNS... :book: <iframe src="https://giphy.com/embed/xT5LMu7NN4BwQBhhcc" width="480" height="362" frameBorder="0" class="giphy-embed" allowFullScreen></iframe> --- ## Before SNS... :book: Communication via API calls... ...that needed to be polled for updates synchronously... ...one-to-one server/client relationship ...hard to scale to multiple services ...complex error handling --- SNS acts as a single **message bus** that can send messages to a variety of devices and platforms :bus: --- A message bus is: > A communication system that transfers data between services, > **without each service needing to know about each other** :bus: --- This benefit is known as "fire and forget" :fire: --- <!-- I imagine some parents sending their kids to school without needing to know anything about where the school is. The school also doesn't need to know where the children came from --> The endpoints don't need to know about each other <iframe src="https://giphy.com/embed/3orif3E4D4YucjKuUU" width="480" height="366" frameBorder="0" class="giphy-embed" allowFullScreen></iframe> --- Each service sends their message to the bus :envelope: :arrow_right: :bus: The bus delivers the message to the appropriate endpoints :bus: :arrow_right: :postbox: --- <!-- basically SNS - a bus driver that knows where it is going, where each passenger needs to get off, what order they need to be dropped off in, whether they need multiple stops --> <iframe src="https://giphy.com/embed/xT5LMNZyLRrzHez8pG" width="480" height="366" frameBorder="0" class="giphy-embed" allowFullScreen></iframe> --- ### Bus Features Uni-directional traffic :arrow_right: <!-- always drives the same route in the same direction, no return journey! --> --- ### Terminology - **Senders** (also known as publishers, producers) :package: - **Receivers** (also known as processors, consumers or subscribers) :nerd_face: --- ### How to use SNS --- 1. Create a topic <!-- This is the bus, or message channel --> ![Screenshot 2023-12-07 at 17.02.23](https://hackmd.io/_uploads/SyAscuJ86.png) --- ![Screenshot 2024-01-03 at 16.19.16](https://hackmd.io/_uploads/SkOztZXOp.png) --- FIFO = no duplicates, order matters, message delivered exactly once :point_up: Standard = messages delivered at least once, there may be duplicates or messages out of order :repeat: --- SNS's core functionality: When you publish a message to a topic, it fans out the message to all subscribed endpoints <!-- Put a message on the bus, and it can duplicate that message to all the endpoints that are interested in it (I'm imagining zombie A* children at all the middleclass schools in the area) or zombie buses --> <iframe src="https://giphy.com/embed/l4hLVfpZQf1Ca0bhm" width="480" height="270" frameBorder="0" class="giphy-embed" allowFullScreen></iframe> --- SNS endpoints (subscribers) could include: - email - SMS (texts) - Lambda functions - HTTP endpoints - SQS queues :eyes: <iframe src="https://giphy.com/embed/efxrDXet2TJILuGRwO" width="480" height="270" frameBorder="0" class="giphy-embed" allowFullScreen></iframe> --- <!-- One common design pattern is called “fanout.” In this pattern, a message published to an SNS topic is distributed to a number of SQS queues in parallel. By using this pattern, you can build applications that take advantage parallel, asynchronous processing. --> <!-- Publish a message to a topic every time a new image is uploaded Separate SQS queues for: - generate thumbnails - image recognition - store metadata about the image --> ![Screenshot 2024-01-02 at 17.39.58](https://hackmd.io/_uploads/r13O96Zda.png) --- <!-- how this looks in terraform coming up --> ![Screenshot 2023-12-07 at 17.03.13](https://hackmd.io/_uploads/Hkg1sd1IT.png) --- How this looks in terraform: ``` module "invited_applicant_details_submitted" { source = "app.terraform.io/oaknorth/aws_sns_topic/aws" version = "1.4.2" sns_topic_name = "onb-authorisation__invited_applicant_details_submitted" subscribed_accounts = [module.terraform_remote_state_aws_organization.outputs.all_accounts["AWS Customer Due Diligence"]] } ``` --- ![Screenshot 2024-01-03 at 12.58.16](https://hackmd.io/_uploads/BJUec0G_T.png) --- <!-- to include the settings --> ![Screenshot 2023-12-07 at 17.03.13](https://hackmd.io/_uploads/Hkg1sd1IT.png) --- <img src="https://hackmd.io/_uploads/ry4fsRzOT.png" height='710px'> --- Create a subscription to a topic ![Screenshot 2024-01-03 at 16.06.34](https://hackmd.io/_uploads/HyKMUW7dT.png) <!-- Will talk about this in a bit, but the SQS queue is our endpoint --> --- ``` resource "aws_sns_topic_subscription" "sns_cdd_business_knowledge_final_approved_subscription_sqs" { topic_arn = module.terraform_remote_state_cdd_business_knowledge.outputs.final_approved_sns_topic.arn protocol = "sqs" endpoint = module.sqs_cdd_business_knowledge_final_approved.arn } ``` --- <!-- Possible settings - Filter policy: A subscription accepts a message only if the message contains attributes that match those specified in the subscription's filter policy. --> ![Screenshot 2024-01-03 at 16.12.11](https://hackmd.io/_uploads/Sk5vDWm_T.png) --- <!-- and in terraform? --> ![Screenshot 2024-01-03 at 16.16.44](https://hackmd.io/_uploads/SkAdubQuT.png) --- <!-- Redrive policy = what to do with messages that haven't been delivered successfully, e.g. max retry count, interaction between DLQ and main queue A dead letter queue is a special queue that temporarily stores messages that cannot be processed, to prevent source queue from overflowing with unprocessed messages. --> ![Screenshot 2024-01-03 at 16.12.45](https://hackmd.io/_uploads/Bk3tD-Xup.png) --- ![Screenshot 2024-01-03 at 16.18.01](https://hackmd.io/_uploads/HyDpuZ7u6.png) --- ## SQS Simple Queue Service --- ### What is SQS? A potential subscriber of SNS, i.e. a message endpoint <iframe src="https://giphy.com/embed/l2Je9YgJWAx1zF8EE" width="480" height="366" frameBorder="0" class="giphy-embed" allowFullScreen></iframe> --- SQS provides a hosted message queue (also known as a mailbox) --- ### Before SQS... :book: The 'producer-consumer problem' --- ### Scenario: **Buffer**: the shared resource that holds data produced by producer and consumed by consumer (i.e. the queue) :inbox_tray: **Producer**: generate data, put it into the buffer, repeat :repeat: **Consumer**: consume data (remove from the buffer), one piece at a time. :knife_fork_plate: --- The challenge :game_die: - Coordinating the producers and consumers efficiently so neither has to wait too long - Avoid problems like data inconsistency or race conditions. --- Rules :spiral_note_pad: - Producer must not insert data when buffer is full - Consumer must not remove data when the buffer is empty - Producers and consumers must not access the buffer simulataneously --- ### The Solution Lock the queue :lock: <!-- This ensures that only one of the consumer and producer can access the queue at once, and they can't interfere with each others operations --> --- In computer science, the lock is called a `mutex` > Before the producer inserts data into the buffer, it acquires the mutex. After inserting the data, it releases the mutex. > > Similarly, before the consumer removes data from the buffer, it acquires the mutex. After removing the data, it releases the mutex. --- ### But... Using mutexes is quite complex :weary: --- ### Mutex complexity - Avoiding deadlocks :skull_and_crossbones: - when each thread is waiting for the other - Starvation :knife_fork_plate: - When one thread is perpetually denied access to a resource due to a high-priority thread being greedy --- ### Mutex complexity - Performance and slow processes :snail: - each thread has to wait for the mutex before it can execute, which can slow down the program - Error handling - If a thread holding a mutex crashes, it can leave the system in an undefined state :ghost: --- Because of this complexity, lots of higher-level abstractions have been developed to handle a lot of these issues for us :muscle: --- :sparkles: SQS :sparkles: <iframe src="https://giphy.com/embed/hjRde3gO0zkqNY6Bqc" width="480" height="270" frameBorder="0" class="giphy-embed" allowFullScreen></iframe> --- In SQS, when a producer sends a message to a queue, it doesn't matter how many consumers are reading from the queue. Each message is processed independently and in isolation. --- Back to the school bus analogy... <!-- the bus takes the kids to school (sometimes several schools at once), and each school is a strict military school where the kids queue up a lot and are dealt with one by one (not necessarily in order, and sometimes twice, but definitely each one is processed!) --> <img src="https://hackmd.io/_uploads/ByTnibX_a.png" height="600px"> --- ![Screenshot 2024-01-04 at 12.11.50](https://hackmd.io/_uploads/rk7qlXE_a.png) --- <img src="https://hackmd.io/_uploads/BkbgZQ4Op.png" height="700"> --- ### Creating an SQS Queue ![Screenshot 2024-01-04 at 11.22.08](https://hackmd.io/_uploads/HypySf4dT.png) <!-- there is fifo and standard in SQS too --> <!-- FIFO/standard are options for queues and topics. The topics do the message processing, and the queues do the message sending --> --- Amazon SQS **standard** queues guarantees **at-least-once delivery**: - storing messages on multiple servers for redundancy - Resending messages if server is not available (this might mean duplicate messages are sent) --- <!-- There is some config that queues need to have --> <img src="https://hackmd.io/_uploads/rJ-KrGEda.png" height="690"> --- <!-- permissions , i.e an access policy is required --> <img src="https://hackmd.io/_uploads/HJEW8zEup.png" height="690"> --- <!-- in terraform --> ![Screenshot 2024-01-04 at 11.29.31](https://hackmd.io/_uploads/Bkws8GV_T.png) <!-- the custom policy document is the permissions --> --- ![Screenshot 2024-01-04 at 11.30.47](https://hackmd.io/_uploads/BySlwfNu6.png) <!-- allows the sourceArn (topic) to send messages to the queue --> --- When a message is delivered, a receipt handle is generated for that delivery and sent to the recipient ![Screenshot 2024-01-03 at 16.49.10](https://hackmd.io/_uploads/HyUMgMXu6.png) --- ![Receipt handles](https://hackmd.io/_uploads/SkYBxzmO6.png) <!-- The receipt handle is needed for deleting the message or changing its visibility --> <!--you can't put a message on a queue and then recall it --> --- ### SQS Message <!-- When you subscribe an Amazon SQS queue to an Amazon SNS topic, you can publish a message to the topic and Amazon SNS sends an Amazon SQS message to the subscribed queue. The Amazon SQS message contains the subject and message that were published to the topic along with metadata about the message in a JSON document. The Amazon SQS message will look similar to the following JSON document. --> ```json { "Type" : "Notification", "MessageId" : "63a3f6b6-d533-4a47-aef9-fcf5cf758c76", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Subject" : "Testing publish to subscribed queues", "Message" : "Hello world! I could be JSON", "Timestamp" : "2012-03-29T05:12:16.901Z", "SignatureVersion" : "1", "Signature" : "EXAMPLEnTrFPa3...", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem", "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:123456789012:MyTopic:c7fe3a54-ab0e-4ec2-88e0-db410a0f2bee" } ``` --- ### What if message delivery fails? :thinking_face: If Amazon SNS cannot access a subscribed endpoint due to a client-side or server-side error: - message delivery will fail :negative_squared_cross_mark: --- :skull: If a dead-letter queue is attached to the subscription: - failed deliveries held in DLQ for further analysis or reprocessing. :face_with_monocle: (this would break the order in a FIFO queue) --- If no dead-letter queue is attached: - (standard queue) the message is retried indefinitely until the retention period is over - then SNS discards the message :wastebasket: --- ### SQS/SNS make a system... <!-- Fault tolerance: SNS and SQS provide fault tolerance by ensuring that messages are not lost if a service is down. They automatically handle retries and failover, making the system more resilient --> - more resilient <!-- - SNS and SQS help in decoupling microservices and distributed systems. Instead of having services communicate directly with each other, they can communicate through SNS or SQS. This helps in reducing the complexity of the system and makes it easier to manage and scale --> - less complex - easier to scale <!-- Asynchronous processing: SNS and SQS allow for asynchronous processing of messages. This means that a service can send a message and continue with other tasks without waiting for the message to be processed. --> - more performant --- ### Used together... :handshake: - fanout capability of SNS - SNS pushes messages to SQS - messages persist in SQS queues --- :heavy_check_mark: SQS: decouple sending and receiving components, without needing concurrency :heavy_check_mark:SNS: sends messages to multiple subscribers without needing polling --- ![image](https://hackmd.io/_uploads/rJa5kQN_p.png) (the end)

    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