Building an AI Music Generator with Next.js: Async Tasks

2026-11-27来源 dev.toEnglish

A music generator makes an interesting web application problem: the form submission is quick, but the work behind it takes minutes.

I'm building Melumi, an AI music generator that turns lyrics or ideas into songs and also supports instrumental music. Once generation begins, a song is usually ready in about 2–3 minutes; queueing before that can add time.

This post describes the high-level task architecture behind that experience. The examples are simplified design sketches, rather than a complete implementation.

Start with a durable task

Keeping a browser request open for the entire generation process ties the experience to a fragile connection. A page refresh or network interruption should not erase the record of work already accepted by the server.

The application creates a task, stores it in the database, and returns an application-owned task ID after the submission has been accepted. The browser uses that ID to ask our application for updates.

That gives the product a stable reference across the request, background processing, and eventual result. The browser does not need to understand the generation system's internal identifiers or response formats.

A simplified public contract can be as small as:

type TaskView = | { id: string; status: "processing" } | { id: string; status: "succeeded"; audioUrl: string } | { id: string; status: "failed"; message: string }; 

This is an illustrative contract. Real implementations may return multiple tracks or additional metadata, but the UI still needs a clear answer: keep waiting, show a playable result, or explain a failure.

Where Next.js fits

In a Next.js App Router application, route handlers form the HTTP boundary: accept a submission, receive a callback, or return a task view. Server-side services coordinate the work, while database operations and media storage stay behind their own interfaces.

The background consumer needs an execution environment that supports its lifetime. Starting a promise inside a request handler does not, by itself, guarantee that the work survives after the response. Durable task and event records are what allow processing to resume; the hosting model determines how the consumer is run.

The main path: a completion callback

For this overview, treat generation as one asynchronous operation with a successful completion callback.

The flow looks like this:

Browser -> Application: submit generation request Application -> Database: create durable task Application -> Generation service: start work Application -> Browser: return application task ID Generation service -> Callback handler: generation completed Callback handler -> Database: persist completion event Background processing -> Object storage: save audio Background processing -> Database: publish successful result Browser -> Application: request current task state Application -> Browser: return playable result 

The callback handler should do a small amount of work: validate the request, associate it with the expected task, persist the event, and respond promptly.

Downloading audio and saving it to object storage happen outside the callback request. A slow transfer should not make the callback endpoint wait for the whole delivery process.

Persisting the event before acknowledging it also gives background processing a durable place to resume from if an application process restarts.

Two kinds of polling, with different jobs

It is useful to distinguish browser polling from server-side reconciliation.

Browser polling answers a UI question: what does our application currently know about this task? It reads the application's stored state. It should not trigger a fresh generation request or query the generation service on every browser poll.

Server-side reconciliation answers a recovery question: has a task stopped receiving updates, and can its actual state be recovered?

Callbacks are the normal path, but a network failure or temporary endpoint outage can prevent one from arriving. A background reconciliation process looks for tasks that have remained unfinished for too long, queries their current generation status, and feeds any recovered completion into the same result-processing path.

Both paths should converge on the same state-transition and persistence rules:

Completion callback -> shared processing -> stored task result Reconciliation query -> shared processing -> stored task result 

The server can limit recovery checks with retry intervals, backoff, and a bounded retry budget. An interrupted status check is evidence that a check failed; it is not automatically evidence that generation failed.

Make completion safe to repeat

A callback can arrive twice. Reconciliation can also discover completion just before a delayed callback arrives.

The system therefore needs to tolerate processing the same result more than once. Repeated delivery must not create duplicate results, repeat expensive storage work unnecessarily, or move a completed task backward.

At a high level, this means:

  • Claim work so concurrent consumers do not both own the same task transition.
  • Use stable result identities and database uniqueness rules.
  • Make state changes conditional on the task's current state.
  • Keep completed states protected from late or conflicting updates.

An in-memory flag cannot provide those guarantees across a process restart or multiple application instances. The coordination needs a durable source of truth.

Separate generation success from delivery readiness

A completion notification tells us that generation finished. The user still needs an audio file that the application can serve reliably.

Our result-processing path saves the generated media to application-controlled object storage and persists the resulting reference. Only after the required result is stored do we expose it as a successful, playable task.

This creates a useful boundary: generation may be complete while delivery is still being retried. A temporary storage error should not immediately force a new generation request.

It also lets the frontend depend on the application's result contract rather than on temporary media locations from the generation process.

Keep the waiting experience honest

For a task that takes minutes, a precise-looking progress bar can imply information the system does not actually have.

A clear processing state, an approximate duration, and a useful failure message can be more helpful. The frontend stops polling at a terminal state and treats a temporary polling error separately from a confirmed task failure.

A refresh should be able to resume a status lookup when the task reference is available and the user is authorized to access it. Knowing a task ID alone should not grant access to someone else's result.

The architectural lesson carries beyond music: durable tasks track accepted work, callbacks report completion, and reconciliation repairs missing updates. Keeping those responsibilities separate makes a long operation easier to recover and explain to the person waiting for it.

Writing disclosure: This article was drafted with AI assistance from the project's documented architecture. The code and flow diagrams are simplified illustrations.

原文:https://www.a8q9.cn/en/article/building-an-ai-music-generator-with-next-js-async-tasks-f82b90.html

相关文章