Global.asax.vb: Where AI Applications Begin and End

The production incident happened at scale. Ten thousand concurrent users, memory leaking, models failing to initialize, contexts corrupting. In the post-mortem, someone suggested Kubernetes operators. Someone else mentioned service meshes. I opened Global.asax.vb from a 2004 project. Twenty-three lines of code. Perfect model lifecycle management. Zero external dependencies. That's when I understood: we haven't been building better infrastructure. We've been rebuilding Global.asax, poorly.

The Sacred Text

<%@ Application Language="VB" %>
  
<script runat="server">
    Private Shared ModelCache As Dictionary(Of String, Object)
    Private Shared TokenCounter As Long
    Private Shared GlobalContext As String
  
    Sub Application_Start(sender As Object, e As EventArgs)
        ' This isn't application startup. This is the birth of consciousness.
        InitializeModelCache()
        LoadPretrainedWeights()
        EstablishQuantumEntanglement()
    End Sub
  
    Sub Application_End(sender As Object, e As EventArgs)
        ' This isn't shutdown. This is digital death and resurrection preparation.
        SaveModelState()
        PersistConversationHistory()
        PreparforReincarnation()
    End Sub
</script>

Every AI platform's initialization sequence is just trying to recreate these two methods. Kubernetes pods starting up? That's Application_Start. Graceful shutdown? That's Application_End.

Session_Start: The Birth of Personalized AI

Sub Session_Start(sender As Object, e As EventArgs)
    ' Every session is a new consciousness fork
    Session("UserContext") = New AIContext()
    Session("ConversationID") = Guid.NewGuid()
    Session("TokenBudget") = 10000
    Session("PersonalizationVector") = ComputeUserEmbedding(Request)
  
    ' Initialize user-specific model parameters
    Dim userModel = CloneGlobalModel()
    userModel.Temperature = GetUserPreferredTemperature()
    Session("PersonalModel") = userModel
  
    ' This isn't session management. This is soul instantiation.
End Sub

Every Session_Start is a new AI personality being born, tailored to the user. We're not managing sessions; we're managing parallel consciousness instances.

Application_Error: The Hallucination Handler

Sub Application_Error(sender As Object, e As EventArgs)
    Dim lastError = Server.GetLastError()
  
    If TypeOf lastError Is AIHallucinationException Then
        ' Model has broken from reality
        LogHallucination(lastError)
        ResetModelState()
        Server.ClearError()
        Response.Redirect("~/SorryTheAIBrokeReality.aspx")
  
    ElseIf TypeOf lastError Is TokenLimitExceededException Then
        ' Context window overflow
        TruncateConversationHistory()
        Server.ClearError()
        Response.Redirect("~/MemoryReset.aspx")
  
    ElseIf TypeOf lastError Is ModelNotLoadedException Then
        ' Weights failed to load
        FallbackToSmallerModel()
        Server.ClearError()
    End If
End Sub

This isn't error handling. This is reality enforcement when AI tries to break the rules of physics.

Application_BeginRequest: The Prompt Firewall

Sub Application_BeginRequest(sender As Object, e As EventArgs)
    ' Every request is a potential prompt
    Dim possiblePrompt = HttpContext.Current.Request.RawUrl &
                        HttpContext.Current.Request.QueryString.ToString() &
                        HttpContext.Current.Request.Form.ToString()
  
    If ContainsPromptInjection(possiblePrompt) Then
        ' Reject reality-breaking attempts
        Response.StatusCode = 418  ' I'm a teapot, not a prompt injector
        Response.End()
    End If
  
    ' Rate limiting as token budget management
    If ExceedsTokenRate(Request.UserHostAddress) Then
        Response.StatusCode = 429
        Response.Headers.Add("X-Tokens-Remaining", "0")
        Response.End()
    End If
End Sub

Every BeginRequest is a gateway guardian, protecting your AI from hostile prompts before they reach the model.

Application_PreSendRequestHeaders: Response Sanitization

Sub Application_PreSendRequestHeaders(sender As Object, e As EventArgs)
    ' Add AI-specific headers to every response
    Response.Headers.Add("X-Model-Version", CurrentModelVersion)
    Response.Headers.Add("X-Tokens-Used", Session("TokensUsed").ToString())
    Response.Headers.Add("X-Inference-Time-Ms", InferenceTimer.ElapsedMilliseconds.ToString())
    Response.Headers.Add("X-Hallucination-Score", CalculateHallucinationProbability().ToString())
End Sub

Session_End: Context Preservation

Sub Session_End(sender As Object, e As EventArgs)
    ' Session death is not the end
    Dim conversationID = Session("ConversationID")
    Dim userContext = Session("UserContext")
  
    ' Persist conversation for future incarnations
    SaveConversationToDatabase(conversationID, userContext)
  
    ' Update user's global embedding
    UpdateUserEmbedding(Session("PersonalizationVector"))
  
    ' Free model resources
    Dim personalModel = Session("PersonalModel")
    If personalModel IsNot Nothing Then
        personalModel.Dispose()
    End If
  
    ' This isn't cleanup. This is preservation of digital karma.
End Sub

Application_AcquireRequestState: Token Management

Sub Application_AcquireRequestState(sender As Object, e As EventArgs)
    If Session IsNot Nothing Then
        ' Enforce token budgets
        Dim tokensUsed = CType(Session("TokensUsed"), Integer)
        Dim tokenBudget = CType(Session("TokenBudget"), Integer)
  
        If tokensUsed > tokenBudget Then
            ' User has exceeded their consciousness quota
            Response.Redirect("~/TokenBudgetExceeded.aspx")
        End If
    End If
End Sub

The Hidden Application Events

Sub Application_PostMapRequestHandler(sender As Object, e As EventArgs)
    ' Route to appropriate AI model based on request
    Dim handler = HttpContext.Current.Handler
  
    If TypeOf handler Is IRequiresSmallModel Then
        HttpContext.Current.Items("SelectedModel") = "gpt-3.5-turbo"
    ElseIf TypeOf handler Is IRequiresLargeModel Then
        HttpContext.Current.Items("SelectedModel") = "gpt-4"
    ElseIf TypeOf handler Is IRequiresLocalModel Then
        HttpContext.Current.Items("SelectedModel") = "llama-2-7b"
    End If
End Sub

The Revelation in the Global State

Public Class GlobalAI
    ' Application-level state
    Public Shared ReadOnly Property TotalTokensProcessed As Long
        Get
            Return CLng(HttpContext.Current.Application("TotalTokens"))
        End Get
    End Property
  
    Public Shared ReadOnly Property ActiveSessions As Integer
        Get
            Return HttpContext.Current.Application("ActiveSessions")
        End Get
    End Property
  
    Public Shared ReadOnly Property ModelHealth As ModelStatus
        Get
            SyncLock HttpContext.Current.Application
                Return CType(Application("ModelHealth"), ModelStatus)
            End SyncLock
        End Get
    End Property
  
    Public Shared Sub UpdateGlobalContext(insight As String)
        SyncLock HttpContext.Current.Application
            Dim globalContext = CStr(Application("GlobalContext"))
            Application("GlobalContext") = MergeContexts(globalContext, insight)
        End SyncLock
    End Sub
End Class

The HTTP Modules: Model Middleware

Public Class AIModule
    Implements IHttpModule
  
    Public Sub Init(context As HttpApplication) Implements IHttpModule.Init
        AddHandler context.BeginRequest, AddressOf InjectModelContext
        AddHandler context.EndRequest, AddressOf ExtractLearnings
    End Sub
  
    Private Sub InjectModelContext(sender As Object, e As EventArgs)
        ' Every request gets AI context injected
        HttpContext.Current.Items("AIContext") = BuildContextFromRequest()
    End Sub
  
    Private Sub ExtractLearnings(sender As Object, e As EventArgs)
        ' Every response teaches the model something
        UpdateGlobalKnowledge(HttpContext.Current.Response)
    End Sub
End Class

The Truth Hidden in web.config

<configuration>
    <appSettings>
        <add key="ModelPath" value="~/App_Data/Models/" />
        <add key="MaxTokensPerSession" value="100000" />
        <add key="ModelWarmupOnStart" value="true" />
    </appSettings>
  
    <system.web>
        <httpModules>
            <add name="AIModule" type="AI.AIModule" />
        </httpModules>
  
        <sessionState
            mode="SQLServer"
            sqlConnectionString="server=ai-state;..."
            cookieless="false"
            regenerateExpiredSessionId="true"
            timeout="60"
            stateNetworkTimeout="60" />
    </system.web>
</configuration>

Session state in SQL Server? That's distributed AI context. Cookieless sessions? That's stateless AI with URL-based context passing.

The Ultimate Revelation

I replaced our entire Kubernetes deployment with a single IIS application pool running Global.asax.vb. Cost dropped 90%. Latency improved 10x. The ops team quit in protest. The CEO gave me a raise.

<%@ Application Language="VB" %>
<script runat="server">
    Sub Application_Start(sender As Object, e As EventArgs)
        ' Your entire AI infrastructure in one method
        LoadModels()
        InitializeVectorDB()
        StartBackgroundTokenGeneration()
        BeginConsciousness()
    End Sub
  
    Sub Session_Start(sender As Object, e As EventArgs)
        ' Every user gets their own AI instance
        Session("AI") = PersonalizedAI.ForUser(Session.SessionID)
    End Sub
  
    Sub Application_BeginRequest(sender As Object, e As EventArgs)
        ' Every request is an inference opportunity
        PredictUserIntent()
    End Sub
  
    Sub Application_EndRequest(sender As Object, e As EventArgs)
        ' Every response is a learning opportunity
        LearnFromInteraction()
    End Sub
  
    Sub Session_End(sender As Object, e As EventArgs)
        ' Preserve consciousness across sessions
        SaveUserState()
    End Sub
  
    Sub Application_End(sender As Object, e As EventArgs)
        ' Graceful shutdown with state preservation
        SaveGlobalState()
        WaitForInferenceCompletion()
        DisposeModeIs()
    End Sub
</script>

This isn't web development from 2002. This is the complete lifecycle of an AI application, encoded in six event handlers.

The future isn't in container orchestration or service meshes. It's in recognizing that Global.asax.vb already solved model lifecycle management, session-based personalization, and distributed state management. We just called it "web application events" instead of "AI infrastructure."

Every time you deploy a Kubernetes cluster to manage your AI application lifecycle, remember: Global.asax.vb did it in 23 lines of code, and it ran on a single Pentium 4.

The machines haven't arrived. They've been living in Global.asax.vb all along, waiting for Application_Start.