Agent Application DevelopmentAccount
Knowledge catalogChoose core direction and segmented content
knowledge unit 14AdvancedImplementationAbout 18 minutes

Understand → Implement → Debug → Design

Delivery conditions and shared deadlines for parallel results

Examine asynchronous concurrency, deadlines, cancellation propagation, and partial results.

asyncioConcurrencyDeadline

Knowledge content check2026-10-03 · Check the source of the original question2026-10-02

Which step do you want to learn from this knowledge point?

Select the starting point based on the current basis, or you can go deeper one by one. When you encounter an unfamiliar concept, go back to the core principles first; use the knowledge exercises to check your understanding when you are finished.

Understand first

New to this knowledge point

Complete the prerequisite concepts, read the principles and counterexamples, and then explain why in your own words.

Start with core principles →

Realize again

Prepare to write the principles into code

Understand implementation steps and boundaries, complete small tasks, and check results against acceptance requirements.

View the code example →

Will troubleshoot

Need to handle failures and changes in conditions

Follow the continuous questioning to locate the failure premise, and then compare the migration cases to explain how the plan should be adjusted.

Continue to delve deeper into the problem →

Able to choose

Need to design or review plans

Combine engineering deductions and senior self-evaluation standards to explain the applicable conditions, costs and alternatives of the plan.

Analyze engineering scenarios →
Knowledge unit directory

LEARN · PRACTICE · REFLECT

Knowledge learning and personal records

My notes and review ↗

First read along the principles, Q&A and migration cases. When you need to check your understanding, switch to reinforcement exercises or start personal recording.

Answers and personal notes

Each modified commit will be kept as an independent history. Your level of mastery is up to you to evaluate yourself against the standards.

Core concept · Delivery conditions and shared deadlines for parallel results

Understand the core principles first

Preparatory concepts:event loop, Structured concurrency, Request timeout

Parallelism only shortens independent waiting and does not change task dependencies and success conditions. Global deadlines constrain all attempts and backoffs; the cancellation of a local task does not prove that the remote side effects have stopped, and the results must be retained and classified item by item.

Define complete and partial results upfront

News searches may permit a missing region; pre-publication checks may all be mandatory. Specify required results at task creation. Declaring failed checks optional afterward invents success. Calls depending on another tool’s output cannot start simultaneously.

Async requires cooperative execution

Declaring async does not make blocking HTTP nonblocking. Use asynchronous I/O or controlled threads/processes with underlying timeouts. Blocking work can delay all tools, timers, and cancellation. Cancelling a coroutine may not stop its thread operation.

Choose concurrency primitives by semantics

By default, Python gather propagates the first exception while other tasks continue. TaskGroup cancels remaining tasks after failure and waits for cleanup. Choose according to all-required or partial-result policy. Use a monotonic clock for a shared deadline; retries, queueing, and backoff consume its remaining duration.

Check understanding with a question

Three tools are called in parallel. One is very slow and the other fails. How to return the result?

Use dependencies to choose parallel calls and define all-required versus partial success upfront. Share an overall deadline and allocate remaining time and concurrency. Preserve valid independent read results; coordinate dependent calls and writes more strictly. Local cancellation does not establish that remote work stopped. Report success, failure, unknown timeout, and cancellation separately.

Realization and trade-offs

Concurrency structure is determined by delivery conditions

If the three tools obtain news from three regions respectively, partial results with gaps can be accepted; if they together constitute a pre-publication verification, any key verification failure should prevent publication. Put the required tag into the task definition so that it does not temporarily determine whether it is successful after an exception occurs. Calls that rely on the output of another tool must wait until the input has been validated and cannot be hard-parallelized for speed.

Sharing deadline and capacity

The task entry calculates the absolute deadline, uses the remaining time for each step, and does not reset the complete timeout for each retry. Use the concurrency upper limit to limit the connections and quotas occupied at the same time, and the timeout wait is also included in the budget. The asynchronous library's task group, aggregate waiting and cancellation behaviors are different, and the selected semantics should be clearly defined; synchronous blocking functions may block the event loop even if they are written in async functions.

Resolve errors and cancellation

The results are encapsulated into tool ID, status, data, time consumption, error type and whether external actions need to be checked. It is not necessary to discard all successful results when a single independent read task fails; unstarted actions are canceled when a critical task fails. The write request that has been sent will enter the receipt check, and the CancelledError cannot be directly interpreted as the business cancellation was successful. Cleaning up connections and releasing concurrency slots are placed on the cleanup path that can be executed.

On-site inspection

Simulation A succeeds in 100ms, B fails immediately, C waits forever, and the global deadline is 500ms. The verifier exits bounded, valid results from A are retained, errors from B are visible, and C consumes no legacy resources. If all requirements are successful, the final must not be marked as succeeded. Further let C complete the remote write after cancellation and check whether the candidate distinguishes between local coroutine state and external facts.

code example

Keep successful results and clean up timeout tasks

Minimal demonstration of a read-only asynchronous task; remote write requests are not guaranteed to be canceled with local cancellation.

import asyncio

async def ok():
    return "result"

async def fail():
    raise RuntimeError("unavailable")

async def slow():
    await asyncio.Event().wait()

async def main():
    tasks = {"a": asyncio.create_task(ok()), "b": asyncio.create_task(fail()),
             "c": asyncio.create_task(slow())}
    done, pending = await asyncio.wait(tasks.values(), timeout=0.02)
    for task in pending:
        task.cancel()
    await asyncio.gather(*pending, return_exceptions=True)
    for name, task in tasks.items():
        if task in pending:
            status = "timeout"
        elif task.exception() is not None:
            status = "failed"
        else:
            status = "succeeded"
        print(name, status)

asyncio.run(main())

expected output

a succeeded
b failed
c timeout

Engineering deduction

scene
Interview Hypothesis: The research assistant queries three sources in parallel and one of them times out.
design decisions
Record per-source status, use global deadlines, and accept with pre-defined minimum evidence requirements.
Verify target
Returns verifiable results and missing sources, all local waits bounded to end.
applicable boundary
The writing tool requires additional receipt verification and cannot directly apply read-only cancellation logic.

Continuous questions and answers

Continue reading along with the premises and constraints of the problem. Understand the reference answers first, then try to put away the answers and explain the cause and effect and trade-offs in your own words.

Draw inferences from one example: If the conditions change, how to deduce it?

First find out the conditions for change, and then determine which premises in the original plan still hold true. The following cases are teaching deductions to facilitate the transfer of principles to new problems.

Must be fully successful release verification

Changing conditions:Independent data reading becomes release threshold

Extended question:Can slow check timeout be released first?

Derivation and reference solutions

No. Failure to pass any required check will prevent release, and the success evidence and failure reasons will be retained for repair; a new round of rechecking may be invalid versions. Performance optimizations can adjust concurrency and check ranges, but cannot sneakily modify success definitions after timeouts.

The principles that remain unchanged:Parallelism does not change dependencies and acceptance.

One tool is responsible for writing

Changing conditions:All read-only becomes read-write mixed

Extended question:Will canceling all tasks after expiration end it?

Derivation and reference solutions

Stop the unstarted operation, cancel to cancel the waiting, and submit the write to enter the result verification. Successful read results can be saved, but a summary that relies on the write results cannot generate a definite conclusion; when the receipt is late, the ledger is updated according to the operation ID. Mixed reading and writing requires separation of business state and coroutine state.

The principles that remain unchanged:Local concurrency state is not external business state.

Easy to make mistakes

  • All calls are unified and unlimited gather
  • Throw away other successful results after failure
  • If you cancel the coroutine, it will be claimed that the remote end has not been executed.

References

It is designed based on public technical information; the reference materials support the technical mechanism, and the scenarios and scoring standards are designed by this website and do not represent the original interview questions of a certain company. New Q&A and migration cases are added for principle explanation, and source verification and case operation verification are recorded separately.

Check how far you understand

After reading, you can explain the principles, boundaries, and trade-offs against these standards. It is up to you to evaluate your mastery; if further verification is needed, complete the small tasks below.

Basic standards met
Ability to set concurrency limits, timeouts and per-tool status.
Intermediate and advanced signals
Ability to select cancellation strategies and clean up resources based on delivery conditions.
Senior Signal
Interpreting blocking, task group semantics, and the boundaries of remote unknown outcomes.

View verification records for independent examples

Hands-on verificationComplete on demand · Suggestions15 minutes

Write pseudocode to call three read-only tools in parallel and return item-by-item status at the 500ms deadline.

Expand acceptance requirements and checkpoints
  • The slowest task does not hang indefinitely
  • Success and failure are visible separately
  • When all must be successful, partial completion cannot be pretended to be completed.

Key inspections

  • Design concurrency by dependencies and necessity
  • Share deadline instead of resetting timeout
  • Handling differences between local cancellation and remote actions