Can anyone help me optimize my respawn code?

Hello,

I just need help optimizing my code, if any one knows a better way to do this I would be grateful!

Server Script:

local runService = game:GetService("RunService")
local deathPos = {}

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		runService.Heartbeat:Wait()

		if deathPos[player] then
			character:SetPrimaryPartCFrame(deathPos[player])
		end

		local humanoid = character:FindFirstChildOfClass("Humanoid")
		local primaryPart = character.PrimaryPart

		local function onRunning()
			if humanoid and humanoid:GetState() == Enum.HumanoidStateType.Running then
				
				local raycastParams = RaycastParams.new()
				raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
				raycastParams.FilterDescendantsInstances = {character}

				local raycastResult = game.Workspace:Raycast(primaryPart.Position, Vector3.new(0, -999999999999999, 0), raycastParams)

				if raycastResult then
					--print("Ray hit the ground at:", raycastResult.Position)
					local yOffset = primaryPart.Size.Y
					deathPos[player] = CFrame.new(raycastResult.Position + Vector3.new(0, yOffset + 2, 0))
					--local material = raycastResult.Material -- Uncomment if you want to use material
				end
			end
		end

		local timer = 0

		runService.Heartbeat:Connect(function(deltaTime)
			timer = timer + deltaTime
			if timer >= 0.75 then
				onRunning()
				timer = 0
			end
		end)
	end)
end)

game.Players.PlayerRemoving:Connect(function(player)
	deathPos[player] = nil
end)

You should consider running the onRunning logic over the client and passing it to the server on death. Then have the server validate that the position of death taken from the client is close enough to the servers detection of death.