Hang Yin
    • 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
    # Scheduler ## The requirements The demand of scheduler comes from multiple sources. Including automated Offchain Rollup job (PW Game, Request-Response pattern), workflow engine, and more. Phat Contract queries can be registered in a scheduler with cron-style expression, and the scheduler takes care of the following things: - **Scheduling**: Parse and trigger tasks defined by cron-style expression - **Accuracy**: Ideally the fire of a task should happen exactly once on a worker. However due to technical limitations, we may offer best-effort trigger accuracy. In other worlds, minimize skips and redundant trigger. - **Scalability**: The scheduler should offload the execution of the triggered tasks on remote workers, instead of running locally. - **Realiability**: The scheduler itself shouldn't be the single point of failure. ## Simple scheduler Let's start from the easiest case. Suppose there's only one worker and very limited amount of the jobs. The scheduler saves the job definitions to the contract storage. The job is defined by a cron expression, the target contract address, and the call data. Each time the scheduler wakes up, it should go through all the jobs and trigger the job that's ready to fire. When the scheduler finish one round of the check, it becomes idle until the next wake-up. The first problem is how to decide if a job should be triggered or not. In a typical backend service, the scheduler can simply calculate the next fire time of a task based on the cron expression and the current time, store it somewhere, and when it passes, the trigger fires once. It can be described as the following pseudocode: ```rust // Parse an cron expression with `saffron` let cron: Cron = "*/10 0 * OCT MON".parse().unwrap(); let mut next = cron.next_from(Utc::now()).unwrap(); loop { // If the deadline passes, trigger the task if Utc::now() > next { fire(); next = cron.next_from(Utc::now()).unwrap(); } sleep(1); } ``` However, in Phat Contract the scheduler should be run as a query. Queries are event driven without the support of long running tasks or contract storage. The sleep loop can be replaced by a `poll()` query to wake up the scheduler. The `poll()` function will need to know and update the next fire time. Without the access to the contract storage, it needs to either store the time in an external storage (e.g. S3), or the in-memory cache offered by Phat Contract. The Phat Contract cache is a simple KV-store resides in the worker's memory provided to every contract. It's volatile and never sync betwee the workers. So there's no guarantee of data availability in case of worker shutdown. It cannot be used to store any serious, but for the case of a simple scheduler, it's already good enough to store the next fire time: - If the worker hosting the scheduler runs smoothly, the scheduler should run as expected - If the cache lost happens, it simply re-calculates the next fire time. Considering the following cases: 1. If the data lost happened before the fire time, nothing is lost 2. If the data lost happened right between two `poll()` calls around the fire time, the task will be skipped once 3. If the data lost happen after the `poll()` call following the fire time, the fire time should have been updated. So it's equivalent to the first case The cache data lose only happens occasionally. So we can concludes that if the `poll()` happens more frequently compared with the cron job fires, the missed fire should be very rare. So we can say it follows the **Accuracy** principle. The pseodocode can be: ```rust fn register(&mut self, cron_expr: String, target: Target) { let cron: Cron = cron_expr.parse().unwrap(); self.job = Some((cron, target)); } fn poll(&self) { const KEY_NEXT: &str = "next"; let (cron, target) = self.job?; if let Some(cached_next) = ext().cache_get(KEY_NEXT) { let next = DateTime::decode(cached_next).unwrap(); if Utc::now() > next { // Trigger if it passes the fire time target.fire(); } else { // Otherwise, wait until next poll return } } // Update the next fire time anyway let next = cron.next_from(Utc::now()); ext().cache_set(KEY_NEXT, next.encode()); } ``` Reference implementation: <https://github.com/Phala-Network/phat-stateful-rollup/blob/main/phat/contracts/local_scheduler/lib.rs> ## Offload task to remote workers The simple scheduler achieves **Scheduling**, and (best-effort) **Accuracy**. It can easily scale from a single job to a few, but to achieve **Scalability**, we should move the execution of the tasks to remote workers to avoid computation bottleneck. By offloading the execution, a single thread scheduler is supposed to scheduler thousands of jobs. The remote worker-to-worker call is done via simple HTTP requests. It implies the scheduler should be able to access the execution workers via the internet by their publicly registered RPC endpoints. Since the scheduler could trigger up to thousands of concurrent HTTP requests, the ink! contract model doesn't work anymore, because the HTTP request in ink! is blocking operation. Instead, the scheduler should run as a SideVM program. By moving to remote execution, two problems raise: - How to distribute the tasks smartly? - Remote execute could fail. How to ensure **Accuracy**? ### Task distribution A good task distribution mechanism should take full use of all the available workers. In other words, it should minimize the computation on the hot spot worker (the worker with the largest workload). It assumes the task can be executed on any worker, and thus the execution should be stateless. (There are well-known tricks to convert stateful application to stateless services.) A simple strategy is to randomly distribute the tasks. It can be further optimized by considering the actual invocation or running time on each worker. In addition, the job assignment may be persisted or cached locally, because some job may still prefer to stick to a worker to take use of its local cache (e.g. an IPFS data fetcher). In case some workers go down, after a few failure reported from that worker, it can be temporarily removed from the worker pool. Health check can also be used to proactively maintain the worker pool. ### Idempotence Remote execution could fail due to the internet packet lose or even the lose of the worker. In such case, it must be possible to retry the tasks. Here's a potential strategy: Once the scheduler gets any failed fire, it can switch to trigger the task on another worker. It keeps retrying until making the first successful response. However, this strategy may introduce unexpected redundant call. For example, in the first try the HTTP request was sent and the task was executed remotely, but due to the unstable network, the response was lost, and the scheduler starts another try since it doesn't know the execution was done. This is a [typical problem](https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/#cron-job-limitations) in all schedulers, and can be avoided by an **idempotent design**. By definition, if all the tasks are idempotent, the retry will not cause any damage. In practice, each execution of a job can be assigned with an unique id (i.e. `task_id`). The `task_id` can be a self-incremental id that increases by time. With the `task_id`, the target can deduplicate the query request from the scheduler. The handler can store the recent `task_id` in its local cache, and drop any future call with the same `task_id`. For the app with very strong consistency requirement, it can persist the invocation to external database or even a blockchain (e.g. OffchainRollup) to make it strongly idempotent. Thousands of jobs is a reasonable estimation of the capacity of a single-worker scheduler. The accurate capacity must be measured by real world benchmark. To handle an even larger scale of the jobs, we may need to create multiple schedulers. ## High availability Finally, the **Reliability** of the system requires the scheduler itself must be redundant. This is a typical High Availability scenario and there are a lot of well-studied solutions in the distributed system industry. The scheduler itself has to be either fully replicated, or be hosted by an elected master. If the tasks are strongly idempotent, the full replication approach could work but with additional network overhead. For weakly idempotent tasks, full replication requires the jobs should mostly distributed by the fixed worker so that they can deduplicate the tasks with their local cache. Mainstream solutions all point to the election-based method. A cluster of nodes governed by a consensus algorithm (e.g. Raft) can be used to elect a master, and only let the master to run the scheduler. However, implementing a full consensus on top of Phat Contract is still a great amount of the work to do. In practice, the two approaches can be combined to build a minimum-centralized scheduler. Instead of running a real high availability cluster, some off-chain HA cluster can be used to monitor a pool of workers, and choose one worker to call the scheduler's `poll()` entry. Since the HA cluster is centralized, theoretically it can duplicate the poll query maliciously. However thanks to the idempotent requirement of the cron tasks, the jobs themselves can deduplicate the call, and thus limit the damage to the system. ## Conclusion This docs presents how to design a Phat Contract scheduler that can ensure four requirements. It will be build in SideVM, trigger the tasks on remote workers with idempotency considered to achieve high accuracy, and use an external trigger to achieve high availability.

    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