0Pricing
Supabase Backend as a Service · บทเรียน

คิวงานด้วยซูเปอร์เบสและผู้ประมวลผลงาน

สำรวจแนวทางการประมวลผลงานเบื้องหลังและคิวข้อความโดยใช้ซูเปอร์เบสกับบริการผู้ประมวลผลงานภายนอก

คิวงานด้วยซูเปอร์เบสและผู้ประมวลผลงาน เป็นบทเรียน Supabase Backend as a Service ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Supabase Backend as a Service และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Supabase Backend as a Service มีบทเรียนทั้งหมด 3 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Tasks: Background vs. Foreground

Imagine your app needs to send a welcome email, process a large image, or generate a report. If your user has to wait for these long tasks to finish, their experience suffers.

These are background tasks: operations that don't need immediate user interaction and can run independently without blocking the user interface.

Introducing Task Queues

A task queue (or message queue) is a system that allows different parts of your application to communicate asynchronously. It acts like a temporary holding area for tasks.

  • Producers: Add tasks to the queue.
  • Consumers (Workers): Pick up tasks from the queue and process them.

This decouples the task creation from its execution.

Why Use a Task Queue?

Task queues bring several key benefits to your application architecture:

  • Improved Responsiveness: Users don't wait for long operations.
  • Scalability: You can add more workers to handle increased load.
  • Reliability: Tasks can be retried if they fail.
  • Decoupling: Separates task submission from task execution.

Supabase as a Simple Queue

While Supabase isn't a dedicated message queue, its powerful PostgreSQL database can serve as a simple task queue for many use cases. We can create a dedicated table to store tasks.

A typical tasks table might have columns like:

  • id (Primary Key)
  • payload (JSONB, for task data)
  • status (e.g., 'pending', 'processing', 'completed', 'failed')
  • created_at (Timestamp)
  • processed_at (Timestamp, nullable)

Enqueueing Tasks (Producer)

To enqueue a task, your client-side application or API endpoint simply inserts a new row into the tasks table with a 'pending' status. The payload column holds all the necessary data for the worker to process.

For example, to send a welcome email after user signup:

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseKey = 'YOUR_SUPABASE_ANON_KEY';
const supabase = createClient(supabaseUrl, supabaseKey);

async function enqueueWelcomeEmail(userId, email) {
  const { data, error } = await supabase
    .from('tasks')
    .insert({
      type: 'send_welcome_email',
      payload: { userId, email },
      status: 'pending'
    });

  if (error) {
    console.error('Error enqueueing task:', error.message);
  } else {
    console.log('Welcome email task enqueued!');
  }
}

// Example usage (not runnable directly without Supabase setup)
// enqueueWelcomeEmail('user123', 'test@example.com');

Introducing External Workers

An external worker is a separate application or service that continuously monitors the task queue for new jobs. When it finds a 'pending' task, it picks it up, processes it, and updates its status.

Workers can be written in any language (Node.js, Python, Go) and run on various platforms (servers, serverless functions, containers). They connect to your Supabase database to read and update task records.

Dequeueing Tasks (Consumer/Worker)

A worker needs to:

  1. Fetch 'pending' tasks.
  2. Mark a task as 'processing' to prevent other workers from picking it up.
  3. Execute the task logic using the payload.
  4. Update the task status to 'completed' or 'failed'.

Workers can either poll (periodically check) or use Supabase's Realtime feature to listen for new task insertions.

Code: Simple Worker Logic (Polling)

Here's a simplified Node.js worker logic that polls the Supabase tasks table every few seconds. Remember to replace placeholder values.

// worker.js
const { createClient } = require('@supabase/supabase-js');

const SUPABASE_URL = 'YOUR_SUPABASE_URL';
const SUPABASE_KEY = 'YOUR_SUPABASE_SERVICE_ROLE_KEY'; // Use service key for workers
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);

async function processTask(task) {
  console.log(`Processing task ${task.id}: ${task.type}`);
  // Simulate work (e.g., sending email, processing image)
  await new Promise(resolve => setTimeout(resolve, 2000));
  console.log(`Task ${task.id} processed.`);
  // In a real app, this would involve calling an email API etc.
}

async function runWorker() {
  console.log('Worker started, looking for tasks...');
  setInterval(async () => {
    try {
      // Fetch one pending task and lock it by updating status
      const { data: tasks, error } = await supabase
        .from('tasks')
        .select('*')
        .eq('status', 'pending')
        .order('created_at', { ascending: true })
        .limit(1);

      if (error) throw error;

      if (tasks.length > 0) {
        const task = tasks[0];
        // Atomically update status to 'processing'
        const { error: updateError } = await supabase
          .from('tasks')
          .update({ status: 'processing', processed_at: new Date().toISOString() })
          .eq('id', task.id)
          .eq('status', 'pending'); // Ensure no other worker picked it up

        if (updateError) {
          if (updateError.code === '40600') { // Row already updated by another process
            console.log(`Task ${task.id} already picked up.`);
            return; 
          }
          throw updateError;
        }

        await processTask(task);

        // Update status to 'completed'
        await supabase
          .from('tasks')
          .update({ status: 'completed' })
          .eq('id', task.id);

      } else {
        // console.log('No pending tasks.');
      }
    } catch (err) {
      console.error('Worker error:', err.message);
      // Implement error handling, e.g., update task status to 'failed'
    }
  }, 5000); // Poll every 5 seconds
}

// To run this: node worker.js
// (Requires 'npm install @supabase/supabase-js' and a Supabase project)
runWorker();

Task States & Reliability

Properly managing task states is crucial for reliability:

  • Pending: Task is waiting to be processed.
  • Processing: Worker has picked up the task.
  • Completed: Task finished successfully.
  • Failed: Task encountered an error.

For failed tasks, you might implement retries (e.g., after a delay) and ensure tasks are idempotent (running them multiple times has the same effect as running once) to prevent unintended side effects.

Queueing Question

You've learned about using Supabase and external workers for task queues. Consider a scenario where a user uploads a large video file that needs transcoding.

Recap: Task Queues & Workers

We've explored how task queues enable efficient background processing in your applications. By using Supabase as a simple queue and external workers, you can:

  • Offload long-running operations.
  • Improve user experience by keeping your app responsive.
  • Build more scalable and robust systems.

This pattern is fundamental for building complex, high-performance web and mobile applications.

คำถามที่พบบ่อย

บทเรียน “คิวงานด้วยซูเปอร์เบสและผู้ประมวลผลงาน” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “คิวงานด้วยซูเปอร์เบสและผู้ประมวลผลงาน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Supabase Backend as a Service ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Supabase Backend as a Service มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “คิวงานด้วยซูเปอร์เบสและผู้ประมวลผลงาน”

สำรวจแนวทางการประมวลผลงานเบื้องหลังและคิวข้อความโดยใช้ซูเปอร์เบสกับบริการผู้ประมวลผลงานภายนอก คุณปฏิบัติ Supabase Backend as a Service ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Supabase Backend as a Service หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Supabase Backend as a Service บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน

บทเรียน “คิวงานด้วยซูเปอร์เบสและผู้ประมวลผลงาน” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Supabase Backend as a Service นี้ได้ไหม

ได้ บทเรียน Supabase Backend as a Service ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การผสานรวมกับบริการภายนอก
  2. คิวงานด้วยซูเปอร์เบสและผู้ประมวลผลงาน
  3. การจัดกำหนดการงานที่ทำซ้ำด้วย pg_cron
← กลับไปที่ Supabase Backend as a Service