सामग्री पर जाएँ

लेसन 47 · Asynchronous Programming

AsyncLocalStorage और Context

Node.js में AsyncLocalStorage सीखें: run और getStore, request context, logs में correlation IDs, nested stores, snapshot, bind, गलतियाँ और diagnostics_channel।

एक ऐसे server की कल्पना करें जो एक साथ कई requests संभाल रहा है। हर request का अपना user, अपनी correlation ID और अपना शुरू होने का समय है। आपके कोड की गहराई में, request handler से तीन फ़ंक्शन (function) कॉल दूर, आप ऐसी log लाइन लिखना चाहते हैं जिसमें वह correlation ID हो। उस फ़ंक्शन को कैसे पता चले कि वह किस request के लिए काम कर रहा है?

सीधा जवाब है हर फ़ंक्शन में context आर्ग्युमेंट (argument) पास करना। यह काम करता है, पर हर signature को भर देता है, और जो library आपने नहीं लिखी, उसे इसे आगे बढ़ाना नहीं सिखाया जा सकता। दूसरी भाषाएँ इसके लिए "thread-local" वेरिएबल (variable) इस्तेमाल करती हैं। Node.js में एक ही thread है और उस पर हज़ारों आपस में गुँथे async operations चलते हैं, इसलिए thread-locals का कोई मतलब नहीं। Node का जवाब है AsyncLocalStorage: ऐसा storage जो आपके कोड के asynchronous flow के साथ चलता है, await, timers, promises और callbacks के पार, ताकि एक request के अंदर शुरू हुआ कोड सिर्फ़ उसी request का data देखे।

यह lesson दिखाता है कि यह कैसे काम करता है, request context और logging में इसे कैसे इस्तेमाल करें, और इसके जाल क्या हैं। यह Promises in Depth, The Event Loop और Events and EventEmitter पर आधारित है।

बुनियादी बातें: run और getStore

एक AsyncLocalStorage instance बनाएँ, आम तौर पर मॉड्यूल (module) के स्तर पर। store को जोड़कर callback चलाने के लिए als.run(store, callback) कॉल करें। उस callback के अंदर कहीं भी, और जो कुछ वह asynchronous रूप से शुरू करता है उसमें, als.getStore() वही value लौटाता है। किसी भी run के बाहर यह undefined लौटाता है।

Node.js run() एक value को अंदर की हर चीज़ के लिए उपलब्ध करता है

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

showUser कोई parameter नहीं लेता, फिर भी run के अंदर सही user प्रिंट करता है और बाहर (no context) पर लौट आता है। value callback के execution से जुड़ी होती है, फ़ंक्शन से नहीं।

async सीमाओं को पार करना

जादू यह है कि store asynchronous काम के साथ-साथ चलता है। वह await, setTimeout, प्रॉमिस (promise) callbacks, process.nextTick और I/O callbacks के पार बना रहता है। और एक ही समय में चल रही दो run calls एक-दूसरे की value कभी नहीं देखतीं, भले ही वे एक ही thread पर आपस में गुँथी हों।

Node.js आपस में गुँथे दो flows अलग stores रखते हैं

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

output देखें: हर लाइन उस job का नाम दिखाती है जिसने उसे प्रिंट किया, भले ही दोनों jobs बारी-बारी चलती हैं। अगर ये कदम सादे global वेरिएबल होते, तो job B, job A की value मिटा देती और output गलत होता। साथ-साथ चलते flows का आपस में क्रम timing पर निर्भर करता है, इसलिए असली प्रोग्राम को उस पर निर्भर नहीं होना चाहिए; गारंटी सिर्फ़ यह है कि हर flow अपना ही store पढ़ता है।

Request context और correlation IDs

इसका क्लासिक उपयोग logging है। एक छोटा log फ़ंक्शन context पढ़ता है ताकि हर लाइन में request की ID हो, और आपके किसी business फ़ंक्शन को इसके बारे में कुछ जानने की ज़रूरत न पड़े।

Node.js request ID अपने-आप जोड़ने वाला logger

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

असली HTTP server में आप requestContext.run(...) एक बार, middleware के पहले टुकड़े में, बाकी पूरी handling के चारों ओर कॉल करेंगे (Middleware Pattern देखें)। उसके बाद का सब कुछ, आपकी database calls समेत, वही ID देखता है। production के logging patterns के लिए Logging and Observability देखें।

असली server में IDs crypto.randomUUID() से बनाएँ, या आने वाले X-Request-Id header को मानें ताकि एक ही ID कई services के पार request के साथ चले। ऊपर का demo सिर्फ़ इसलिए counter इस्तेमाल करता है ताकि output हर बार एक-सा रहे।

store में क्या रखा जा सकता है

store कोई भी value हो सकता है: स्ट्रिंग (string), ऑब्जेक्ट (object), Map। आम तौर पर ऑब्जेक्ट चुने जाते हैं क्योंकि request आगे बढ़ने पर आप उसमें और data जोड़ सकते हैं। ध्यान दें कि run reference स्टोर करता है, इसलिए ऑब्जेक्ट में किया बदलाव उसी flow के हर फ़ंक्शन को दिखता है।

Node.js बदलने योग्य store flow के दौरान data इकट्ठा करता है

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

बदला जा सकने वाला context सुविधाजनक है, पर अपने flow के अंदर वह global की तरह व्यवहार करता है, इसलिए उसे छोटा और अच्छे नामों वाला रखें। अगर आपको immutability चाहिए, तो उसे बदलने के बजाय नई run कॉल पर store बदल दें।

Nesting और exit

एक run के अंदर दूसरा run कॉल करने से अपने store वाला अंदरूनी scope बनता है; अंदर वाला callback खत्म होने पर बाहरी store फिर दिखने लगता है। als.exit(callback) callback को बिना किसी store के चलाता है, जो ऐसे background काम के लिए उपयोगी है जिसे request का context विरासत में नहीं मिलना चाहिए।

Node.js Nested run और exit

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

आम गलतियाँ

वहाँ store पढ़ना जहाँ कोई है ही नहीं

जब कोई run सक्रिय न हो तो getStore() undefined लौटाता है: startup कोड में, पहली request से पहले बनाए गए timer में, या कहीं और से आए event में। जो कोड मान लेता है कि store होगा, वह उलझाने वाले error के साथ crash होता है।

Node.js यह भूलना कि store गायब हो सकता है (जानबूझकर फ़ेल)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

नतीजा है TypeError: Cannot read properties of undefined (reading 'requestId')। हल यह है कि गायब होने वाली स्थिति को जानबूझकर संभालें: als.getStore()?.requestId ?? 'none'। logger को request के बाहर भी काम करते रहना चाहिए।

ऐसे callbacks जो किसी और के context में चलते हैं

context उस कोड के पीछे चलता है जिसने काम को schedule किया। ज़्यादातर APIs में आपको यही चाहिए। लेकिन किसी साझा ऑब्जेक्ट (event emitter, connection pool, queue) पर register किया callback उसी के context में चलता है जो उसे ट्रिगर करता है, और वह register करने वाला context नहीं भी हो सकता। नीचे का listener एक run के अंदर register हुआ था, पर उस run के अंदर चलता है जो emit कॉल करता है।

Node.js Event listeners को emitter का context दिखता है

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

यही असर connection pools में भी दिखता है: request 1 के दौरान खुला pooled कनेक्शन अपने callbacks request 2 के context से कॉल कर सकता है। libraries इसे AsyncResource से या context को साफ़-साफ़ capture करके हल करती हैं।

context पकड़ना: bind और snapshot

दो helpers आपको context ऐसी जगह ले जाने देते हैं जहाँ वह वरना खो जाता। AsyncLocalStorage.bind(fn) ऐसा फ़ंक्शन लौटाता है जो हमेशा उस context में चलता है जो bind कॉल करते समय सक्रिय था। AsyncLocalStorage.snapshot() ऐसा फ़ंक्शन लौटाता है जो किसी भी callback को पकड़े गए context के अंदर चलाता है।

Node.js bind और snapshot मौजूदा context पकड़ते हैं

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

enterWith: सावधानी से इस्तेमाल करें

als.enterWith(store) बिना callback के, मौजूदा synchronous execution के बाकी हिस्से और उसके शुरू किए हर काम के लिए store सेट करता है। इस तरीके से context का रिसाव आसान है, क्योंकि कुछ भी यह नहीं बताता कि scope कहाँ खत्म होता है। run को प्राथमिकता दें। enterWith को सही ठहराने वाली एक जगह ऐसा framework hook है जो बाकी काम को callback में नहीं लपेट सकता।

याद रखने की और बातें

  • Performance. async context की निगरानी हर async operation पर थोड़ी लागत लेती है। आधुनिक Node (24) में लागत कम है और per-request context के लिए AsyncLocalStorage ठीक है, पर हज़ारों instances न बनाएँ और store में विशाल ऑब्जेक्ट न रखें।
  • हर काम के लिए एक instance. एक बड़े थैले के बजाय अलग-अलग चीज़ों (request context, transaction, tracing) के लिए अलग AsyncLocalStorage ऑब्जेक्ट रखें।
  • application state की जगह नहीं. इसे आसपास के, हर flow के metadata के लिए इस्तेमाल करें। business data को अब भी आर्ग्युमेंट के रूप में पास करें।
  • Tests. जो tests कोड को run के बाहर चलाते हैं, उन्हें कोई store नहीं दिखता, जिससे आम तौर पर यह bug सामने आता है कि कोड गायब context को कैसे संभालता है।

async_hooks और diagnostics_channel: एक छोटी सैर

AsyncLocalStorage, node:async_hooks मॉड्यूल में रहता है, जिसकी पुरानी, निचले स्तर की createHook() API हर async resource के जन्म, शुरू होने और खत्म होने की सूचना देती है। application कोड के लिए createHook() इस्तेमाल न करें: यह धीमी है और इसका status experimental है। AsyncResource उन library लेखकों के लिए सपोर्टेड निचले स्तर का tool है जो अपनी queues या pools लपेटते हैं; इससे आप कह सकते हैं, "इस callback को उस context में चलाओ जो मेरे बनते समय मौजूद था"।

एक पड़ोसी tool diagnostics_channel है: नाम वाले channels जिन पर libraries events publish करती हैं और observability tools उन्हें subscribe करते हैं, और library को उन पर निर्भर नहीं होना पड़ता। बिना subscriber वाले channel पर publish करना लगभग मुफ़्त है।

Node.js diagnostics_channel पर publish और subscribe

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node के अपने http, net और fetch भी diagnostic channels publish करते हैं, और tracing tools उन्हें AsyncLocalStorage के साथ इस्तेमाल करके आपके पूरे प्रोग्राम में एक request का पीछा करते हैं। Debugging and Diagnostics में और जानकारी है।

कब इस्तेमाल करें, और कब नहीं

AsyncLocalStorage को ऐसे cross-cutting context के लिए इस्तेमाल करें जिसे वरना आपको हर कॉल से गुज़ारना पड़ता: request IDs, authenticated user, tenant, transaction handles, tracing spans, locale। जब सादा फ़ंक्शन आर्ग्युमेंट काफ़ी साफ़ हो, तो इससे बचें: साफ़-साफ़ parameters पढ़ने, test करने और refactor करने में आसान हैं। अगर किसी फ़ंक्शन को काम करने के लिए चुपचाप आसपास की state चाहिए, तो उसे दस्तावेज़ में लिखें, और store गायब होने पर उसे साफ़ message के साथ फ़ेल कराएँ।

अपनी समझ जाँचें

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. जब कोई als.run() सक्रिय न हो, तो als.getStore() क्या लौटाता है?

    किसी भी run() के बाहर getStore() undefined लौटाता है। कोड को यह स्थिति संभालनी चाहिए, जैसे optional chaining से।
  2. 2. दो requests एक ही समय पर, अपने-अपने als.run() के अंदर संभाली जा रही हैं। getStore() से हर एक क्या पढ़ती है?

    store asynchronous flow के साथ चलता है, इसलिए एक ही thread पर गुँथे flows एक-दूसरे से अलग रहते हैं।
  3. 3. एक event listener एक run() के अंदर register हुआ, पर event दूसरे के अंदर emit हुआ। डिफ़ॉल्ट रूप से listener को कौन-सा store दिखता है?

    listeners synchronous रूप से emit कॉल के context में चलते हैं। register वाले context को पक्का करने के लिए AsyncLocalStorage.bind() इस्तेमाल करें।
  4. 4. als.exit(callback) क्या करता है?

    exit() callback को मौजूदा context के बाहर चलाता है, जो ऐसे background काम के लिए उपयोगी है जिसे request का data विरासत में नहीं मिलना चाहिए।
  5. 5. आम तौर पर enterWith() की जगह run() को क्यों प्राथमिकता दी जाती है?

    enterWith() मौजूदा execution के बाकी हिस्से के लिए store बदल देता है और उसका कोई दिखने वाला अंत नहीं होता, जिससे अनजाने रिसाव आसान हो जाते हैं।

सारांश

  • AsyncLocalStorage हर फ़ंक्शन से parameters गुज़ारे बिना कोड को हर flow की आसपास वाली value देता है।
  • als.run(store, fn) fn और उसके asynchronous रूप से शुरू किए हर काम के लिए store सेट करता है; als.getStore() उसे पढ़ता है और run के बाहर undefined लौटाता है।
  • गुँथे हुए flows अलग-थलग रहते हैं, इसलिए यह request IDs, users, transactions और tracing के लिए आदर्श है।
  • साझा ऑब्जेक्ट पर callbacks उन्हें ट्रिगर करने वाले caller के context में चलते हैं; context पकड़ने के लिए AsyncLocalStorage.bind() या snapshot() इस्तेमाल करें।
  • enterWith से ज़्यादा run को प्राथमिकता दें, stores छोटे रखें, और "कोई store नहीं" वाली स्थिति हमेशा संभालें।
  • diagnostics_channel libraries को ऐसे events publish करने देता है जिन्हें tools subscribe करते हैं; async_hooks.createHook() निचले स्तर का tool है जिससे आपको बचना चाहिए।

आगे: net के साथ TCP Servers और Clients

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।