GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — BigQuery: make jobs awaitable · Issue #15742 · googleapis/google-cloud-python

BigQuery: make jobs awaitable #15742

New issue
Copy link
New issue
Copy link
Open
Open
BigQuery: make jobs awaitable#15742
Copy link
Assignees
tswast
Labels
Python 3 OnlyThis work would involve supporting Python 3 only code paths.api: bigqueryIssues related to the BigQuery API.type: feature request‘Nice-to-have’ improvement, new feature or different behavior or design.

Description

@dkapitan
dkapitan
opened on Jul 21, 2019
Issue body actions

I know BigQuery jobs are asynchronous by default. However, I am struggling to make my datapipeline async end-to-end.

Looking at this JS example, I thought it would be the most Pythonic to make a BigQuery job awaitable. However, I can't get that to work in Python i.e. errors when await client.query(query). Looking at the source code, I don't see which method returns an awaitable object.

I have little experience in writing async Python code and found this example that wraps jobs in a async def coroutine.

class BQApi(object):                                                                                                 
    def __init__(self):                                                                                              
        self.api = bigquery.Client.from_service_account_json(BQ_CONFIG["credentials"])                               

    async def exec_query(self, query, **kwargs) -> bigquery.table.RowIterator:                                       
        job = self.api.query(query, **kwargs)                                                                        
        task = asyncio.create_task(self.coroutine_job(job))                                                          
        return await task                                                                                            

    @staticmethod                                                                                                    
    async def coroutine_job(job):                                                                                    
        return job.result()   

The google.api_core.operation.Operation shows how to use add_done_callback to asynchronously wait for long-running operations. I have tried that, but the following yields AttributeError: 'QueryJob' object has no attribute '_condition' :

from concurrent.futures import ThreadPoolExecutor, as_completed
query1 = 'SELECT 1'
query2 = 'SELECT 2'

def my_callback(future):
    result = future.result()

operations = [bq.query(query1), bq.query(query2)]
[operation.add_done_callback(my_callback) for operation in operations]
results2 = []
for future in as_completed(operations):
  results2.append(list(future.result()))

Given that jobs are already asynchronous, would it make sense to add a method that returns an awaitable?

Or am I missing something and is there an Pythonic way to use the BigQuery client with the async/await pattern?

Reacted by Riccardo Albertazzi, Jeff Laughlin, Jonathan Lange, Zeb Barnett, Prratek Ramchandani, Nik B, Anthony Clark, Vitaliy, Shinichi TAMURA, Víctor Martín Molina and 31 more
Reacted by Hutch

Activity

Next
  1. tseaver commented on Jul 22, 2019

    @tseaver
    tseaver
    on Jul 22, 2019
    Contributor
    More actions

    @dkapitan Re: the async await / async def keywords: our codebase straddles both Python2 and Python3 until at least the end of this year, and thus cannot adopt the syntax directly in the codebase until we drop Python2 support.

    We might be able to tweak the google.api_core.operation.Operation class to support that usage at a low level. Can you please post the traceback for the AttributeError?

    Also, for your example above, your callback isn't doing anything with result: it is being called from a helper thread, and would need to do something to signal the main thread

  2. dkapitan commented on Jul 22, 2019

    @dkapitan
    dkapitan
    on Jul 22, 2019
    Author
    More actions

    @tseaver thanks for clarifying. I have read up more on concurrent.futures and asyncio. I understand the latter is indeed quite new and Python 3 only. Will investigate the sample code a bit more, and get to you with the results and/or the traceback.

  3. dkapitan commented on Jul 24, 2019

    @dkapitan
    dkapitan
    on Jul 24, 2019
    Author
    More actions

    @tseaver here's traceback from the AttributeError

    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-19-e9025f68a561> in <module>
          9 [operation.add_done_callback(my_callback) for operation in operations]
         10 results2 = []
    ---> 11 for future in as_completed(operations):
         12   results2.append(list(future.result()))
    
    /usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py in as_completed(fs, timeout)
        217     fs = set(fs)
        218     total_futures = len(fs)
    --> 219     with _AcquireFutures(fs):
        220         finished = set(
        221                 f for f in fs
    
    /usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py in __enter__(self)
        144     def __enter__(self):
        145         for future in self.futures:
    --> 146             future._condition.acquire()
        147 
        148     def __exit__(self, *args):
    
    AttributeError: 'QueryJob' object has no attribute '_condition'
    
  4. dkapitan commented on Jul 24, 2019

    @dkapitan
    dkapitan
    on Jul 24, 2019
    Author
    More actions

    @tseaver
    For now, I have decided to do the following:

    import numpy as np
    from time import sleep
    
    
    query1 = """
    SELECT
      language.name,
      average(language.bytes)
    FROM `bigquery-public-data.github_repos.languages` 
    , UNNEST(language) AS language
    GROUP BY language.name"""
    query2 = 'SELECT 2'
    
    
    def dummy_callback(future):
        global jobs_done
        jobs_done[future.job_id] = True
    
    
    jobs = [bq.query(query1), bq.query(query2)]
    jobs_done = {job.job_id: False for job in jobs}
    [job.add_done_callback(dummy_callback) for job in jobs]
    
    # blocking loop to wait for jobs to finish
    while not (np.all(list(jobs_done.values()))):
        print('waiting for jobs to finish ... sleeping for 1s')
        sleep(1)
    
    print('all jobs done, do your stuff')
    

    Rather than using as_completed I prefer to use the built-in async functionality from the bigquery jobs themselves. This also makes it possible for me to decompose the datapipeline into separate Cloud Functions, without having to keep the main ThreadPoolExecutor live for the duration of the whole pipeline. Incidentally, this was the reason why I was looking into this: my pipelines are longer than the max timeout of 9 minutes for Cloud Functions (or even 15 minutes for Cloud Run).

    Downside is I need to keep track of all the job_ids across the various functions, but that is relatively easy to solve when configuring the pipeline by specifying inputs and outputs such that they form a directed acyclic graph.

    Any suggestions are welcome. Would be nice if at some point in the future, Google's api future plays nicely with Python's future (no pun intended).

  5. tseaver commented on Jul 24, 2019

    @tseaver
    tseaver
    on Jul 24, 2019
    Contributor
    More actions

    @dkapitan Thanks for the follow-up. I agree that it would be ideal if jobs could be awaited.

    You could simplify your example code using a set, e.g.:

    from time import sleep
    
    query1 = """
    SELECT
      language.name,
      average(language.bytes)
    FROM `bigquery-public-data.github_repos.languages` 
    , UNNEST(language) AS language
    GROUP BY language.name"""
    
    query2 = 'SELECT 2'
    
    queries = [query_1, query_2]
    
    awaiting_jobs = set()
    
    def callback(future):
        awaiting_jobs.discard(future.job_id)
    
    for query in queries:
        job = bq.query(query)
        awaiting_jobs.add(job.job_id)
        job.add_done_callback(callback)
    
    while awaiting_jobs:
        print('waiting for jobs to finish ... sleeping for 1s')
        sleep(1)
    
    print('all jobs done, do your stuff')
    Reacted by northtree, Will, Tycho-1, Jay Kubo, Justice Yi Zheng, DK and Yohei Okabayashi
    Reacted by Túlio Lima and DK
  6. dkapitan commented on Jul 24, 2019

    @dkapitan
    dkapitan
    on Jul 24, 2019
    Author
    More actions

    @tseaver
    Nice, thanks. Never thought of using a set to do a kind of countdown ... 😄

  7. northtree commented on Aug 22, 2019

    @northtree
    northtree
    on Aug 22, 2019
    More actions

    @tseaver Thanks for the simplify example. Could you fix two typos?

    awaiting_jobs.discard(future.job_id)

    job = bq.query(query)

  8. tseaver commented on Aug 27, 2019

    @tseaver
    tseaver
    on Aug 27, 2019
    Contributor
    More actions

    @northtree Thanks for catching those: updated.

  9. sambcom commented on Sep 6, 2019

    @sambcom
    sambcom
    on Sep 6, 2019
    More actions

    How do you get the rows from your different queries? Won't this block on job.result() What am I missing?

  10. dkapitan commented on Oct 10, 2019

    @dkapitan
    dkapitan
    on Oct 10, 2019
    Author
    More actions

    @sambcom
    apologies for the late response; forgot to subscribe to this issue.
    In my use case, the results of the query are explicitly written to new tables, as part of an ELT pipeline. So that's no issue.

    I understand that generically speaking, you could write query results to (temporary) tables in BigQuery, so this should not be a blocking issue.

  11. zbarnett commented on Oct 30, 2019

    @zbarnett
    zbarnett
    on Oct 30, 2019
    More actions

    I just ran into this problem myself and found out that even though the job itself is "asynchronous" there are actually two places where synchronous I/O is happening.

    From the example usage on https://googleapis.dev/python/bigquery/latest/index.html

    from google.cloud import bigquery
    
    client = bigquery.Client()
    
    # Perform a query.
    QUERY = (
        'SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` '
        'WHERE state = "TX" '
        'LIMIT 100')
    query_job = client.query(QUERY)  # API request
    rows = query_job.result()  # Waits for query to finish
    
    for row in rows:
        print(row.name)

    client.query(QUERY) makes a synchronous network request as does query_job.result()

    Usually, blocking on result() takes the majority of the time, but I've seen cases where query() can take over a second to complete by itself.

    As a workaround for now, I'm running all the BigQuery data fetching code in a separate thread to free up the event loop but it would be fantastic if the BigQuery API supported async I/O.

    Example workaround (code fragment):

    def get_data(client, query):
        return client.query(query).result()
    
    loop = asyncio.get_running_loop()
    data = await loop.run_in_executor(None, get_data, client, query)
    Reacted by Vitaliy, Hermano Lustosa, Phutares Suwannarat and Raquel-Cerqueira
  12. yan-hic commented on Nov 12, 2019

    @yan-hic
    yan-hic
    on Nov 12, 2019
    More actions

    We too have hundreds of load and dedupe queries running async. We do use futures but only to submit the jobs at once and get the id's.

    From there we poke regularly the Stackdriver logging (using airflow) for the status of all in one API call.
    Waiting for blocking result() is inefficient if you only want to know when jobs are done.

    I wish get_job() could support multiple jobids but the API doesn't and an enhancement request has stalled.

  13. tswast commented on Nov 12, 2019

    @tswast
    tswast
    on Nov 12, 2019
    Contributor
    More actions

    We've identified EOL for new versions of the BigQuery client library as January 1, 2020 in #9036 We can revisit this request after that date.

    Reacted by Anthony Clark
  14. plamut
    transferred this issue fromgoogleapis/google-cloud-pythonon Feb 4, 2020
  15. product-auto-label
    added
    api: bigqueryIssues related to the BigQuery API.
    on Feb 4, 2020
  16. 40 remaining items

  17. tswast commented on Dec 17, 2025

    @tswast
    tswast
    on Dec 17, 2025
    Contributor
    More actions

    @bhuesemann I definitely understand the frustration. Async Python is not a "new" feature anymore. Thanks for the reminder. I'll see what I can do to push this forward.

    Reacted by Andrew S and Brian Dobray
  18. tswast
    assigned
    tswast
    and unassigned
    kiraksi
    on Dec 17, 2025
  19. bhuesemann commented on Dec 21, 2025

    @bhuesemann
    bhuesemann
    on Dec 21, 2025
    More actions

    @tswast Thanks for your reply. I appreciate your efforts to move this foreward. But to be honest: I've lost hope that this will get priority (if not as part of something else). For me async processing is such a basic, essential thing especially for these naturally IO bound tasks. It keeps complexity low and provides easy scalability with minimal overhead. It should be imperative for such kind/type of APIs and the natural design choice. Thanks Tim, I know it can be sometimes hard to convice people to invest in such things. Please try what you can do as you said.

    Reacted by Tim Sweña (Swast) and Shelby Smith
  20. Tunneller commented on Dec 22, 2025

    @Tunneller
    Tunneller
    on Dec 22, 2025 via email
    More actions
    I’m going the 3.14t route. I have Cloud Run running free threaded and the browser ends up triggering ~3 parallel (nonoverlapping) queries to BQ, but for the download I get iterative PyArrow pages and I send each page off to a thread. So this is more-or-less async. Maybe better. Regards, From: bhuesemann ***@***.***> Sent: Sunday, December 21, 2025 01:38 PM To: googleapis/python-bigquery ***@***.***> Cc: John Lovell ***@***.***>; Comment ***@***.***> Subject: Re: [googleapis/python-bigquery] BigQuery: make jobs awaitable (#18) <https://avatars.githubusercontent.com/u/906138?s=20&v=4> bhuesemann left a comment (googleapis/google-cloud-python#15742) <#15742 (comment)> @tswast <https://github.com/tswast> Thanks for your reply. I appreciate your efforts to move this foreward. But to be honest: I've lost hope that this will get priority (if not as part of something else). For me async processing is such a basic, essential thing especially for these naturally IO bound tasks. It keeps complexity low and provides easy scalability with minimal overhead. It should be imperative for such kind/type of APIs and the natural design choice. Thanks Tim, I know it can be sometimes hard to convice people to invest in such things. Please try what you can do as you said. — Reply to this email directly, view it on GitHub <#15742 (comment)> , or unsubscribe <https://github.com/notifications/unsubscribe-auth/AEMBZGPTFOSD5K7OHQRIN6L4C3ZITAVCNFSM6AAAAABRZPHLB6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZTMNZZGMZDIMRXGY> . You are receiving this because you commented. <https://github.com/notifications/beacon/AEMBZGPDCMEJLJN6L6QVTH34C3ZITA5CNFSM6AAAAABRZPHLB6WGG33NNVSW45C7OR4XAZNMJFZXG5LFINXW23LFNZ2KUY3PNVWWK3TUL5UWJTW3JYEHI.gif> Message ID: ***@***.*** ***@***.***> >
  21. shelbylsmith commented on Feb 18, 2026

    @shelbylsmith
    shelbylsmith
    on Feb 18, 2026
    More actions

    Pretty please address this issue. The difference async makes in performance/usability is massive.

    Reacted by Matei Simtinică and Shelby Smith
  22. Tunneller commented on Feb 18, 2026

    @Tunneller
    Tunneller
    on Feb 18, 2026
    More actions

    Is this still pertinent now that Python has released the GIL ? I'm running 3.14t noGIL on Cloud Run with individual threads downloading from BQ and everything is in parallel. No async within the thread, but hey, I have 8 threads. And yes, much faster.

  23. shelbylsmith commented on Feb 18, 2026

    @shelbylsmith
    shelbylsmith
    on Feb 18, 2026
    More actions

    @Tunneller Yes it is pertinent or they would simply remove asyncio from python after the GIL changes. The GIL wasn't the bottleneck because the operations are mostly IO bound; nearly all IO operations actually release the GIL while doing syscalls. 8 threads means 8 concurrent requests maximum. That's pretty bad performance if they're doing a lot of waiting. Suppose you needed to run 8 queries in parallel to service a request, your container instance can only handle one request a time, which might be compounded if you need to thread things other than bigquery queries. Combine this with the fact that you don't have to fumble with threads or be concerned about thread-safety.

  24. Tunneller commented on Feb 19, 2026

    @Tunneller
    Tunneller
    on Feb 19, 2026
    More actions

    Ah yes, I had missed that it is not uncommon for asyncio users to launch hundreds of calls. You make a good point that threads are a finite and relatively expensive resource, and if you're using them for I/O waiting you're squandering them, even if they are (now) parallel.

  25. bhuesemann commented on Feb 26, 2026

    @bhuesemann
    bhuesemann
    on Feb 26, 2026
    More actions

    Please note that async, multi-processing and multi-threading are different concepts and relate to different use-cases for parallel processing. This use-case (db client query/processing) is inherently an IO-bound task (e.g. network IO-waits) and thus the typical use-case for async. Using a different concept for this is simply wrong and introduces unnecessary overhead and complexity (like handling concurrency).

  26. Tunneller commented on Feb 26, 2026

    @Tunneller
    Tunneller
    on Feb 26, 2026
    More actions

    BigQuery splits large downloads into multiple parallel streams via the Storage Read API, where each stream is a potentially blocking/synchronous operation, so threading is not inappropriate — we're not waiting on a single IO response but managing multiple concurrent blocking downloads, which is exactly the use-case for a thread pool. But I did not mean to imply no role for async.

    Changing subject, slightly, I saw this: gcloud-aio-bigquery. Could that offer faster downloads?

  27. bhuesemann commented on Feb 26, 2026

    @bhuesemann
    bhuesemann
    on Feb 26, 2026
    More actions

    Take a look here for an explanation: https://stackoverflow.com/a/79619730. Having true async support (also async iterators/generators) we could process multiple queries and their results in parallel on a single thread on the client using coroutines. gcloud-aio-bigquery seems to be a good async alternative to execute and process queries. Using the Google Storage API you have already async support on the client side (but a different use case).

  28. Tunneller commented on Feb 28, 2026

    @Tunneller
    Tunneller
    on Feb 28, 2026
    More actions

    Sure, but this really needs to be a request to BQ guys. I am but a humble user.

  29. chalmerlowe commented on Mar 2, 2026

    @chalmerlowe
    chalmerlowe
    on Mar 2, 2026
    Contributor
    More actions

    This issue was moved from the following repo as part of the monorepo migration: googleapis/python-bigquery

  30. chalmerlowe
    transferred this issue fromgoogleapis/python-bigqueryon Mar 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

  • @tswast
    tswast

Labels

Python 3 OnlyThis work would involve supporting Python 3 only code paths.api: bigqueryIssues related to the BigQuery API.type: feature request‘Nice-to-have’ improvement, new feature or different behavior or design.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

    You are visitor 01402775 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.